A - 往復パトロール / Round-Trip Patrol 解説 by admin
GPT 5.2 HighOverview
This problem asks you to find the total travel time when repeating the trip from the waiting area (checkpoint \(N\)) to checkpoint \(1\) and back \(M\) times.
Analysis
The key observation is that the action taken each time the alarm rings is exactly the same every time.
- The checkpoints are arranged in a straight line, and moving between adjacent checkpoints takes \(1\) second, so the distance is the absolute difference of their numbers.
- The waiting area is checkpoint \(N\), and the destination to check is always checkpoint \(1\).
Therefore, the movement for each alarm is the following round trip: - Going: The time from \(N \to 1\) is \(|N-1| = N-1\) seconds - Returning: The time from \(1 \to N\) is also \(N-1\) seconds
In total, each trip takes \(2(N-1)\) seconds.
A naive approach of “adding up \(M\) trips in a loop” is mathematically correct, but since the constraint is \(M \le 10^9\), which is very large, looping would exceed the time limit (causing TLE). Instead, we can compute the time for one trip and simply multiply by \(M\), which calculates instantly.
Concrete example: - When \(N=4\), one round trip is \(3\) seconds from \(4 \to 1\) and \(3\) seconds from \(1 \to 4\), totaling \(6\) seconds - For \(M=5\) trips, the total is \(6 \times 5 = 30\) seconds
Algorithm
- Compute the time for one round trip: \(2(N-1)\)
- Since this is repeated \(M\) times, the answer is \(2(N-1)M\)
- Output the above expression directly
Complexity
- Time complexity: \(O(1)\)
- Space complexity: \(O(1)\)
Implementation Notes
Since \(N, M\) can be up to \(10^9\), the answer can be as large as \(2 \times (10^9-1) \times 10^9 \approx 2 \times 10^{18}\). Python’s
inthas arbitrary precision, so there is no overflow concern (in other languages, 64-bit integers are required).No loop is needed; simply output the expression
2 * (N - 1) * Mdirectly.Source Code
import sys
def main():
N, M = map(int, sys.stdin.readline().split())
print(2 * (N - 1) * M)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
投稿日時:
最終更新: