公式

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

gemini-3-flash-thinking

概要

バラバラになった \(N\) 両の車両の連結情報(前後の車両番号)を基に、列車の先頭から最後尾までの正しい順序を復元する問題です。

考察

この問題は、データ構造の「連結リスト(Linked List)」を構築し、それを先頭から辿る問題と言い換えることができます。

重要なポイントは以下の2点です: 1. 列車の先頭を見つける: 連結情報のうち、\(prev_i = 0\) となっている車両 \(i\) が列車のスタート地点(先頭)です。 2. 次の車両を高速に参照する: ある車両 \(i\) の次に連結されている車両 \(next_i\) を、毎回探すのではなく、配列などを用いて \(O(1)\) で参照できるようにしておく必要があります。

もし、次の車両を探すために毎回全車両を走査してしまうと、1両見つけるのに \(O(N)\) かかり、全体で \(O(N^2)\) の時間がかかってしまいます。\(N=10^5\) のため、これでは制限時間に間に合いません。配列 next_node[車両番号] = 次の車両番号 を作成することで、この問題を解決できます。

アルゴリズム

  1. データの格納: 長さ \(N+1\) の配列 next_node を用意します。 各車両 \(i\) について、入力された \(next_i\) を next_node[i] に格納します。
  2. 先頭車両の特定: 入力の際、\(prev_i = 0\) であるような車両番号 \(i\) を変数 head に記録しておきます。
  3. 列車の走査: current = head とし、以下の操作を current が \(0\)(最後尾の次)になるまで繰り返します。
    • 現在の車両番号 current を記録する。
    • current を next_node[current] に更新して、次の車両に移動する。
  4. 結果の出力: 記録した車両番号を順番に出力します。

計算量

  • 時間計算量: \(O(N)\) 入力の読み込みに \(O(N)\)、先頭から最後尾までの走査に \(O(N)\) かかるため、全体で \(O(N)\) です。
  • 空間計算量: \(O(N)\) 車両の連結情報を保持する配列 next_node や、結果を格納するリストに \(O(N)\) のメモリを使用します。

実装のポイント

  • 高速な入出力: \(N\) が最大 \(10^5\) と大きいため、Pythonでは input() を繰り返すよりも sys.stdin.read().split() などを使って一括で入力を読み込む方が実行時間を短縮できます。

  • 配列のインデックス: 車両番号が \(1\) から \(N\) であるため、配列のサイズを \(N+1\) にしておくと、車両番号をそのままインデックスとして扱えるため実装がスムーズになります。

    ソースコード

import sys

def solve():
    # Read all input at once for efficient processing
    # sys.stdin.read().split() handles all whitespace and is generally fast in Python
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    # The first value is the number of cars
    n = int(input_data[0])
    
    # next_node[i] will store the car number that is connected to the tail side of car i
    # Since car numbers are from 1 to N, we use an array of size N + 1
    next_node = [0] * (n + 1)
    head = -1
    
    # The input provides connection information for each car i (1 to N)
    # The information for car i is located at data[2*i - 1] (prev_i) and data[2*i] (next_i)
    for i in range(1, n + 1):
        # prev_i: car on the head side, next_i: car on the tail side
        prev_i = int(input_data[2 * i - 1])
        next_i = int(input_data[2 * i])
        
        # Map car i to its successor
        next_node[i] = next_i
        
        # If prev_i is 0, car i is the start of the train
        if prev_i == 0:
            head = i
            
    # Traversal from the head car to the tail car
    # We follow the next_node pointers until we reach 0 (the end of the train)
    current = head
    result = []
    # Since it's guaranteed to be a single chain of N cars, the loop runs exactly N times
    while current != 0:
        result.append(str(current))
        current = next_node[current]
        
    # Output the car numbers in order, each on a new line
    sys.stdout.write('\n'.join(result) + '\n')

if __name__ == '__main__':
    solve()

この解説は gemini-3-flash-thinking によって生成されました。

投稿日時:
最終更新: