B - 数直線を進む / Walking on the Number Line 解説 by admin 印刷ページ
swe-2-highAlgorithm
Maintain Takahashi’s current coordinate in a variable position, initialized to 0. Process the moves in input order. For each move, add X_i if D_i is R, and subtract X_i if D_i is L. Immediately after each update, print the resulting value of position. There is no need to store the input in an array; each line can be processed as it is read.
Correctness Proof
Consider the invariant that, before each iteration, position equals Takahashi’s coordinate after all previously completed moves.
- Base case: Before any moves, Takahashi is at coordinate
0, andpositionis initialized to0, so the invariant holds. - Inductive step: If the
i-th move isR, the new coordinate is the old coordinate plusX_i. If it isL, the new coordinate is the old coordinate minusX_i. The program performs exactly this update, so the invariant remains true after the iteration.
By induction, the value printed after the i-th move is Takahashi’s coordinate immediately after that move. Since the program processes every move exactly once and in the given order, it prints the required N coordinates in the correct order.
Complexity
- Time:
O(N) - Auxiliary space:
O(1)
The input is processed sequentially, and each output line is written immediately, so no array is used to store the full input or output. There is no tie-breaking because there is no choice or ordering criterion to resolve.
投稿日時:
最終更新: