結果

問題 No.2316 Freight Train
ユーザー lam6er
提出日時 2025-03-20 21:16:40
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 212 ms / 2,000 ms
コード長 1,170 bytes
コンパイル時間 279 ms
コンパイル使用メモリ 82,524 KB
実行使用メモリ 148,820 KB
最終ジャッジ日時 2025-03-20 21:17:32
合計ジャッジ時間 8,654 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

def main():
    import sys
    input = sys.stdin.read
    data = input().split()
    idx = 0
    n = int(data[idx])
    idx += 1
    q = int(data[idx])
    idx += 1
    p = list(map(int, data[idx:idx + n]))
    idx += n
    
    # Adjust p to be 1-based
    p = [0] + p  # p[1..n] are the given P_1 to P_n
    
    root = [0] * (n + 1)  # 1-based
    
    for i in range(1, n + 1):
        if root[i] == 0:
            stack = []
            current = i
            while True:
                stack.append(current)
                parent = p[current]
                if parent == -1:
                    r = current
                    break
                if root[parent] != 0:
                    r = root[parent]
                    break
                current = parent
            for node in stack:
                root[node] = r
    
    # Process queries
    output = []
    for _ in range(q):
        a = int(data[idx])
        idx += 1
        b = int(data[idx])
        idx += 1
        if root[a] == root[b]:
            output.append("Yes")
        else:
            output.append("No")
    print('\n'.join(output))

if __name__ == '__main__':
    main()
0