結果

問題 No.2316 Freight Train
ユーザー iwasikun8iwasikun8
提出日時 2023-05-26 22:32:21
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,032 ms / 2,000 ms
コード長 1,403 bytes
コンパイル時間 311 ms
コンパイル使用メモリ 86,888 KB
実行使用メモリ 274,964 KB
最終ジャッジ日時 2023-08-26 12:36:18
合計ジャッジ時間 20,354 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 77 ms
71,336 KB
testcase_01 AC 75 ms
71,336 KB
testcase_02 AC 74 ms
71,408 KB
testcase_03 AC 726 ms
110,004 KB
testcase_04 AC 472 ms
93,580 KB
testcase_05 AC 386 ms
93,680 KB
testcase_06 AC 276 ms
80,800 KB
testcase_07 AC 673 ms
83,292 KB
testcase_08 AC 489 ms
110,300 KB
testcase_09 AC 598 ms
98,020 KB
testcase_10 AC 629 ms
93,812 KB
testcase_11 AC 569 ms
106,584 KB
testcase_12 AC 661 ms
103,308 KB
testcase_13 AC 736 ms
110,384 KB
testcase_14 AC 768 ms
110,588 KB
testcase_15 AC 805 ms
110,464 KB
testcase_16 AC 754 ms
110,448 KB
testcase_17 AC 742 ms
110,592 KB
testcase_18 AC 737 ms
110,532 KB
testcase_19 AC 766 ms
110,332 KB
testcase_20 AC 767 ms
110,608 KB
testcase_21 AC 737 ms
110,336 KB
testcase_22 AC 733 ms
110,260 KB
testcase_23 AC 1,032 ms
274,964 KB
testcase_24 AC 837 ms
165,984 KB
testcase_25 AC 562 ms
108,296 KB
testcase_26 AC 536 ms
108,180 KB
testcase_27 AC 490 ms
78,532 KB
testcase_28 AC 74 ms
71,168 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

sys.setrecursionlimit(10 ** 9)

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