結果

問題 No.2316 Freight Train
ユーザー iwasikun8iwasikun8
提出日時 2023-05-26 21:49:19
言語 PyPy3
(7.3.15)
結果
RE  
実行時間 -
コード長 1,359 bytes
コンパイル時間 1,107 ms
コンパイル使用メモリ 86,784 KB
実行使用メモリ 110,464 KB
最終ジャッジ日時 2023-08-26 11:10:39
合計ジャッジ時間 17,161 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 64 ms
71,284 KB
testcase_01 AC 63 ms
71,364 KB
testcase_02 AC 63 ms
71,260 KB
testcase_03 AC 656 ms
109,932 KB
testcase_04 AC 429 ms
92,408 KB
testcase_05 AC 330 ms
92,596 KB
testcase_06 AC 246 ms
80,456 KB
testcase_07 AC 562 ms
83,204 KB
testcase_08 AC 437 ms
110,360 KB
testcase_09 AC 566 ms
96,776 KB
testcase_10 AC 558 ms
92,648 KB
testcase_11 AC 480 ms
106,664 KB
testcase_12 AC 568 ms
103,264 KB
testcase_13 AC 658 ms
110,212 KB
testcase_14 AC 757 ms
110,376 KB
testcase_15 AC 671 ms
110,348 KB
testcase_16 AC 671 ms
110,252 KB
testcase_17 AC 654 ms
110,252 KB
testcase_18 AC 649 ms
110,192 KB
testcase_19 AC 642 ms
110,252 KB
testcase_20 AC 668 ms
110,368 KB
testcase_21 AC 642 ms
110,228 KB
testcase_22 AC 630 ms
110,156 KB
testcase_23 RE -
testcase_24 RE -
testcase_25 AC 509 ms
108,300 KB
testcase_26 AC 512 ms
108,020 KB
testcase_27 AC 437 ms
78,472 KB
testcase_28 AC 64 ms
71,156 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, n):
        self.parents = [-1] * n
        self.list_of_size = [1] * n

    def find_root(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find_root(self.parents[x])
            return self.parents[x]
    
    def union(self, x, y):
        root_of_x = self.find_root(x)
        root_of_y = self.find_root(y)

        if root_of_x == root_of_y:
            return
        
        if self.parents[root_of_x] > self.parents[root_of_y]:
            self.parents[root_of_x] = root_of_y
            self.list_of_size[y] += self.list_of_size[x]
        else:
            self.parents[root_of_y] = root_of_x
            self.list_of_size[x] += self.list_of_size[y]

            if self.parents[root_of_x] == self.parents[root_of_y]:
                self.parents[root_of_x] -= 1
    
    def same(self, x, y):
        return self.find_root(x) == self.find_root(y)
    
    def size(self, x):
        return self.list_of_size[self.find_root(x)]

N, Q = map(int, input().split())
P = list(map(int, input().split()))
uf = UnionFind(N)
for i in range(N):
    if P[i] == -1:
        continue
    uf.union(i, P[i]-1)

for j in range(Q):
    A, B = map(int, input().split())
    A -= 1
    B -= 1
    if uf.same(A, B):
        print("Yes")
    else:
        print("No")
0