公式

B - 数直線を進む / Walking on the Number Line 解説 by admin 印刷ページ

gpt-6-astra-medium

Overview

We maintain the current coordinate in a variable, adding or subtracting the distance according to the direction of movement, to find the coordinate immediately after each move.

Analysis

Letting \(\mathrm{pos}\) be the current coordinate, the change in the coordinate due to movement is as follows:

  • Moving a distance of \(X\) in direction R: Add \(X\) to \(\mathrm{pos}\).
  • Moving a distance of \(X\) in direction L: Subtract \(X\) from \(\mathrm{pos}\).

For example, if the movements are R 3, L 5, and R 1 in order, the coordinate changes as \(0 \to 3 \to -2 \to -1\). Therefore, the coordinates to output in order are \(3, -2, -1\).

For this problem, a naive simulation following the problem statement is fast enough to pass. Note that there is no need to repeat the movement of distance \(X\) one unit at a time; the coordinate can be updated with a single addition or subtraction.

Also, we are not only asked for the final coordinate. We need to output the coordinate at that moment after each move is completed.

Algorithm

  1. Read the number of movements \(N\).
  2. Initialize the variable pos, which represents the current coordinate, to \(0\).
  3. Repeat the following \(N\) times:
    • Read the direction \(D_i\) and distance \(X_i\).
    • If \(D_i\) is R, add \(X_i\) to pos.
    • If \(D_i\) is L, subtract \(X_i\) from pos.
    • Output the updated pos.

Initially, pos is \(0\), the starting point. Since we then add the distance corresponding to each move with the correct sign, the updated pos will always be the coordinate immediately after that move.

Complexity

  • Time complexity: \(O(N)\)
    For each move, updating the coordinate and printing the output are performed once.
  • Space complexity: \(O(1)\)
    We do not store the movement history and only use a few variables, such as the current coordinate.

Implementation Details

  • The distance read using input().split() is a string, so convert it to an integer with int().

  • In the solution code, pos += x if d == 'R' else -x adds x if d is 'R' and -x otherwise. Since the direction is restricted to either L or R, this handles both cases.

  • Coordinates can be negative. Maintain them as they are, without taking the absolute value.

  • Execute print(pos) immediately after updating the coordinate. Printing the initial coordinate \(0\) is not required.

    Source Code

# 問題文から独立に実装
n = int(input())
pos = 0
for _ in range(n):
    d, x = input().split()
    x = int(x)
    pos += x if d == 'R' else -x
    print(pos)

This editorial was generated by gpt-6-astra-medium.

投稿日時:
最終更新: