結果

問題 No.2316 Freight Train
ユーザー rlangevinrlangevin
提出日時 2023-05-26 21:25:03
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 544 ms / 2,000 ms
コード長 1,162 bytes
コンパイル時間 302 ms
コンパイル使用メモリ 86,972 KB
実行使用メモリ 110,212 KB
最終ジャッジ日時 2023-08-26 10:00:32
合計ジャッジ時間 13,619 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 65 ms
71,316 KB
testcase_01 AC 64 ms
71,272 KB
testcase_02 AC 63 ms
71,400 KB
testcase_03 AC 537 ms
110,160 KB
testcase_04 AC 412 ms
92,416 KB
testcase_05 AC 383 ms
92,100 KB
testcase_06 AC 222 ms
80,444 KB
testcase_07 AC 358 ms
83,780 KB
testcase_08 AC 494 ms
110,176 KB
testcase_09 AC 473 ms
97,452 KB
testcase_10 AC 429 ms
93,000 KB
testcase_11 AC 484 ms
106,872 KB
testcase_12 AC 478 ms
103,780 KB
testcase_13 AC 541 ms
110,160 KB
testcase_14 AC 533 ms
110,004 KB
testcase_15 AC 525 ms
109,988 KB
testcase_16 AC 539 ms
110,104 KB
testcase_17 AC 523 ms
110,064 KB
testcase_18 AC 544 ms
110,140 KB
testcase_19 AC 531 ms
110,096 KB
testcase_20 AC 521 ms
110,156 KB
testcase_21 AC 535 ms
110,152 KB
testcase_22 AC 513 ms
110,124 KB
testcase_23 AC 187 ms
110,212 KB
testcase_24 AC 187 ms
109,956 KB
testcase_25 AC 175 ms
109,268 KB
testcase_26 AC 164 ms
109,304 KB
testcase_27 AC 118 ms
77,148 KB
testcase_28 AC 64 ms
71,312 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        return self.find(x) == self.find(y)

    def get_size(self, x):
        x = self.find(x)
        return self.size[x]

N, Q = map(int, input().split())
P = list(map(int, input().split()))
U = UnionFind(N)
for i in range(N):
    if P[i] == -1:
        continue
    U.union(i, P[i] - 1)
    
for _ in range(Q):
    A, B = map(int, input().split())
    A, B = A - 1, B - 1
    print("Yes") if U.is_same(A, B) else print("No")
0