B - 数直線を進む / Walking on the Number Line Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
Maintain the current coordinate in a variable and update it according to the specified direction and distance. After each move, print the updated coordinate.
Analysis
On a number line, moving in the positive direction corresponds to adding to the coordinate, and moving in the negative direction corresponds to subtracting from the coordinate.
Letting the current coordinate be \(p\), the coordinate after moving a distance of \(X_i\) is as follows:
- If \(D_i\) is
R: \(p + X_i\) - If \(D_i\) is
L: \(p - X_i\)
For example, moving in the order R 3, L 5, R 1, the coordinate changes as \(0 \to 3 \to -2 \to -1\). Therefore, print \(3\), \(-2\), and \(-1\) each on a separate line.
This problem can be sufficiently solved by a straightforward simulation following the instructions. There is no need to move step-by-step by \(1\); each move can be processed with a single addition or subtraction.
Note that you are not only required to find the final coordinate; you need to output the coordinate immediately after each move.
Algorithm
- Read the number of moves \(N\).
- Initialize a variable
positionrepresenting the current coordinate to \(0\). - Repeat the following process \(N\) times:
- Read the direction \(D_i\) and the distance \(X_i\).
- If \(D_i\) is
R, add \(X_i\) toposition. - If \(D_i\) is
L, subtract \(X_i\) fromposition. - Print the updated
position.
Since the initial coordinate is \(0\) and we correctly add or subtract according to each instruction, position always represents Takahashi’s coordinate at that point. Thus, outputting this after each move yields the correct answer.
Complexity
- Time complexity: \(O(N)\)
For each move, reading input, updating the coordinate, and printing output are each performed once. - Space complexity: \(O(1)\)
Only the current coordinate and the information for the current move are stored.
Implementation Details
- Coordinates can be negative. Print them as they are without converting to absolute values.
- Do not print the initial coordinate \(0\); print only after updating the coordinate.
- Since this code reads input using
sys.stdin.buffer.readline(), the directiondis a bytes object rather than a string. Therefore, compare it withb"R"instead of"R". - The coordinate is updated according to the direction in the following single line:
position += int(x) if d == b"R" else -int(x)
If it is R, a positive distance is added; otherwise (that is, for L), a negative distance is added.
Source Code
import sys
def main():
line = sys.stdin.buffer.readline()
if not line:
return
n = int(line)
position = 0
write = sys.stdout.write
for _ in range(n):
d, x = sys.stdin.buffer.readline().split()
position += int(x) if d == b"R" else -int(x)
write(f"{position}\n")
if __name__ == "__main__":
main()
This editorial was generated by gpt-6-astra-medium.
posted:
last update: