結果

問題 No.2316 Freight Train
ユーザー FromBooskaFromBooska
提出日時 2023-05-27 08:17:11
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 877 ms / 2,000 ms
コード長 1,688 bytes
コンパイル時間 274 ms
コンパイル使用メモリ 87,156 KB
実行使用メモリ 108,864 KB
最終ジャッジ日時 2023-08-26 18:02:02
合計ジャッジ時間 21,159 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 61 ms
71,428 KB
testcase_01 AC 63 ms
71,360 KB
testcase_02 AC 60 ms
71,076 KB
testcase_03 AC 804 ms
108,576 KB
testcase_04 AC 528 ms
91,780 KB
testcase_05 AC 484 ms
91,508 KB
testcase_06 AC 254 ms
79,396 KB
testcase_07 AC 639 ms
83,344 KB
testcase_08 AC 580 ms
108,864 KB
testcase_09 AC 651 ms
96,552 KB
testcase_10 AC 666 ms
91,604 KB
testcase_11 AC 645 ms
105,152 KB
testcase_12 AC 715 ms
101,880 KB
testcase_13 AC 794 ms
108,680 KB
testcase_14 AC 877 ms
108,552 KB
testcase_15 AC 801 ms
108,672 KB
testcase_16 AC 802 ms
108,512 KB
testcase_17 AC 825 ms
108,544 KB
testcase_18 AC 833 ms
108,640 KB
testcase_19 AC 827 ms
108,584 KB
testcase_20 AC 851 ms
108,828 KB
testcase_21 AC 823 ms
108,576 KB
testcase_22 AC 832 ms
108,388 KB
testcase_23 AC 483 ms
108,580 KB
testcase_24 AC 510 ms
108,404 KB
testcase_25 AC 489 ms
106,700 KB
testcase_26 AC 468 ms
106,660 KB
testcase_27 AC 444 ms
78,456 KB
testcase_28 AC 62 ms
71,536 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

# 順序まで求められてないからUnion Findでいいか

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 unite(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()))
UF = UnionFind(N+1)
for i in range(N):
    if P[i] != -1:
        UF.unite(i+1, P[i])

#from collections import defaultdict
#print(UF.all_group_members())

for q in range(Q):
    a, b = map(int, input().split())
    if UF.same(a, b) == True:
        print('Yes')
    else:
        print('No')
0