C - 電車の連結順序 / Train Car Coupling Order 解説 by admin 印刷ページ
gpt-5.3-codexOverview
Since we know the “next connected car (next)” for each car, we can restore the original order by simply finding the head car (prev=0) and following next pointers.
Analysis
The two key observations are:
The head car is uniquely determined
By the problem conditions, there is exactly one car withprev_i = 0. This is the head of the train.Following
nextfrom the head directly gives us the order
Since the input is guaranteed to form a single valid train without contradictions, followingnextfrom the head visits every car exactly once without duplicates, eventually reaching the tail (next=0).
A naive approach of “for each current car, searching through all cars to find the one whose prev matches” would take \(O(N)\) per step, resulting in \(O(N^2)\) overall.
Since \(N \le 10^5\), \(O(N^2)\) is too slow.
Instead, if we store next_i directly in an array nxt[i] during input, we can find the next car in constant time \(O(1)\).
Then we just follow from the head, solving the entire problem in \(O(N)\).
For example:
- 1: (prev=0, next=3)
- 3: (prev=1, next=2)
- 2: (prev=3, next=0)
The head is 1, and following 1 -> 3 -> 2 -> 0 gives the answer 1, 3, 2.
Algorithm
- Read
N. - Prepare an array
nxtof lengthN+1(1-indexed). - For each car
i, read(prev_i, next_i):- Store
nxt[i] = next_i - If
prev_i == 0, recordhead = ias the head car
- Store
- Start with
cur = head, and whilecur != 0:- Append
curto the answer - Move to the next car with
cur = nxt[cur]
- Append
- Output the answer in order.
Complexity
- Time complexity: \(O(N)\)
- \(O(N)\) for reading input, \(O(N)\) for the traversal
- Space complexity: \(O(N)\)
- For storing the
nxtarray and the output array
- For storing the
Implementation Notes
Since car numbers are
1..N, makingnxtof sizeN+1to align indices simplifies the implementation.The output requires
Nlines, so collecting them in a string array and outputting with"\n".join(...)at the end is faster.Using
sys.stdin.readline/sys.stdout.writeensures stable and fast performance even for large inputs.Source Code
import sys
def main():
input = sys.stdin.readline
N = int(input())
nxt = [0] * (N + 1)
head = -1
for i in range(1, N + 1):
prev_i, next_i = map(int, input().split())
nxt[i] = next_i
if prev_i == 0:
head = i
ans = []
cur = head
while cur != 0:
ans.append(str(cur))
cur = nxt[cur]
sys.stdout.write("\n".join(ans))
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.3-codex.
投稿日時:
最終更新: