結果

問題 No.2316 Freight Train
ユーザー 👑 H20H20
提出日時 2023-05-26 21:41:26
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 687 ms / 2,000 ms
コード長 1,677 bytes
コンパイル時間 581 ms
コンパイル使用メモリ 86,904 KB
実行使用メモリ 112,932 KB
最終ジャッジ日時 2023-08-26 10:54:21
合計ジャッジ時間 17,573 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 100 ms
71,676 KB
testcase_01 AC 94 ms
71,628 KB
testcase_02 AC 94 ms
71,732 KB
testcase_03 AC 677 ms
110,944 KB
testcase_04 AC 498 ms
96,616 KB
testcase_05 AC 466 ms
92,748 KB
testcase_06 AC 282 ms
84,180 KB
testcase_07 AC 522 ms
103,080 KB
testcase_08 AC 576 ms
110,292 KB
testcase_09 AC 579 ms
102,480 KB
testcase_10 AC 580 ms
103,664 KB
testcase_11 AC 593 ms
106,096 KB
testcase_12 AC 616 ms
104,772 KB
testcase_13 AC 679 ms
112,060 KB
testcase_14 AC 682 ms
111,436 KB
testcase_15 AC 681 ms
111,112 KB
testcase_16 AC 679 ms
111,828 KB
testcase_17 AC 680 ms
111,852 KB
testcase_18 AC 676 ms
111,240 KB
testcase_19 AC 683 ms
111,856 KB
testcase_20 AC 681 ms
110,972 KB
testcase_21 AC 687 ms
111,780 KB
testcase_22 AC 685 ms
112,932 KB
testcase_23 AC 336 ms
110,712 KB
testcase_24 AC 343 ms
111,068 KB
testcase_25 AC 333 ms
108,288 KB
testcase_26 AC 325 ms
108,064 KB
testcase_27 AC 303 ms
99,372 KB
testcase_28 AC 92 ms
71,668 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

# UnionFind 参考は以下のサイト
# https://note.nkmk.me/python-union-find/
from collections import defaultdict

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

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        group_members = defaultdict(list)
        for member in range(self.n):
            group_members[self.find(member)].append(member)
        return group_members

    def __str__(self):
        return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())


N,Q = map(int, input().split())
P = list(map(int, input().split())) 
AB = [list(map(int, input().split())) for _ in range(Q)]

uf = UnionFind(N+1)
for i,p in enumerate(P,start=1):
    if p>0:
        uf.union(i,p)
for a,b in AB:
    if uf.same(a,b):
        print('Yes')
    else:
        print('No')
0