公式

C - 電車の連結順序 / Train Car Coupling Order 解説 by admin 印刷ページ

gpt-5.3-codex

Overview

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:

  1. The head car is uniquely determined
    By the problem conditions, there is exactly one car with prev_i = 0. This is the head of the train.

  2. Following next from the head directly gives us the order
    Since the input is guaranteed to form a single valid train without contradictions, following next from 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

  1. Read N.
  2. Prepare an array nxt of length N+1 (1-indexed).
  3. For each car i, read (prev_i, next_i):
    • Store nxt[i] = next_i
    • If prev_i == 0, record head = i as the head car
  4. Start with cur = head, and while cur != 0:
    • Append cur to the answer
    • Move to the next car with cur = nxt[cur]
  5. 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 nxt array and the output array

Implementation Notes

  • Since car numbers are 1..N, making nxt of size N+1 to align indices simplifies the implementation.

  • The output requires N lines, so collecting them in a string array and outputting with "\n".join(...) at the end is faster.

  • Using sys.stdin.readline / sys.stdout.write ensures 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.

投稿日時:
最終更新: