A - 数直線上の出会い / Meeting on a Number Line 解説 by admin
gpt-5.3-codexOverview
This is a problem where you simulate the current positions of two people minute by minute at each time step, and count the number of times their coordinates coincide.
It can be solved by converting the characters L/R/S into movement amounts of \(-1/+1/0\) respectively, and updating positions sequentially.
Analysis
The key point is that “meetings” are counted only at integer time instants \(i\).
In other words, you check the coordinates after each minute’s movement, and count it once if they are equal. Even if they pass each other in between, it is ignored.
For example, if during a certain minute:
- Takahashi: 0 → 1
- Aoki: 1 → 0
they cross paths, but since their positions do not match at the end of that time step, it does not count as a meeting.
A naive approach of “storing all positions at each time step in separate arrays and then comparing” would work, but storing them is unnecessary.
All you need is “Takahashi’s current coordinate,” “Aoki’s current coordinate,” and “the meeting count,” so a single pass is sufficient.
The constraint is \(T \le 10^6\), so: - Processing each time step once in \(O(T)\) is fast enough - A double loop of \(O(T^2)\) is obviously not feasible
Algorithm
- Prepare Takahashi’s current position
tx = X, Aoki’s current positionay = Y, and meeting countmeet = 0. - Repeat for \(i=0\) to \(T-1\):
- Update
txaccording toA[i](L:-1, R:+1, S:0) - Update
ayaccording toB[i] - After updating, if
tx == ay, thenmeet += 1
- Update
- Output
meetat the end.
Defining a delta() function for the movement conversion makes the implementation cleaner.
Complexity
- Time complexity: \(O(T)\)
- Space complexity: \(O(1)\) (excluding the input strings)
Implementation Notes
According to the problem statement, time 0 is not counted, so we do not compare at the initial state. The check is performed after movement inside the loop.
Shas a movement amount of 0. An implementation where thedeltafunction treats anything other thanL/Ras0is concise.Since the input size can be large, using
sys.stdin.readlineensures stable and fast performance.Source Code
import sys
def delta(c: str) -> int:
if c == 'L':
return -1
if c == 'R':
return 1
return 0 # 'S'
def main():
input = sys.stdin.readline
T, X, Y = map(int, input().split())
A = input().strip()
B = input().strip()
tx = X
ay = Y
meet = 0
for i in range(T):
tx += delta(A[i])
ay += delta(B[i])
if tx == ay:
meet += 1
print(meet)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.3-codex.
投稿日時:
最終更新: