結果

問題 No.2316 Freight Train
ユーザー nikoro256nikoro256
提出日時 2023-05-26 21:38:09
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 911 ms / 2,000 ms
コード長 1,480 bytes
コンパイル時間 1,106 ms
コンパイル使用メモリ 86,872 KB
実行使用メモリ 111,772 KB
最終ジャッジ日時 2023-08-26 10:47:36
合計ジャッジ時間 22,003 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 86 ms
71,756 KB
testcase_01 AC 86 ms
71,616 KB
testcase_02 AC 85 ms
71,572 KB
testcase_03 AC 862 ms
110,860 KB
testcase_04 AC 629 ms
93,220 KB
testcase_05 AC 540 ms
93,368 KB
testcase_06 AC 276 ms
81,660 KB
testcase_07 AC 702 ms
83,936 KB
testcase_08 AC 678 ms
111,616 KB
testcase_09 AC 730 ms
97,820 KB
testcase_10 AC 758 ms
93,092 KB
testcase_11 AC 762 ms
107,564 KB
testcase_12 AC 813 ms
104,256 KB
testcase_13 AC 863 ms
111,772 KB
testcase_14 AC 891 ms
111,372 KB
testcase_15 AC 882 ms
111,396 KB
testcase_16 AC 889 ms
111,440 KB
testcase_17 AC 878 ms
111,484 KB
testcase_18 AC 866 ms
111,292 KB
testcase_19 AC 894 ms
111,388 KB
testcase_20 AC 900 ms
111,728 KB
testcase_21 AC 910 ms
111,236 KB
testcase_22 AC 911 ms
111,508 KB
testcase_23 AC 519 ms
111,136 KB
testcase_24 AC 546 ms
110,948 KB
testcase_25 AC 536 ms
109,980 KB
testcase_26 AC 522 ms
110,076 KB
testcase_27 AC 484 ms
77,968 KB
testcase_28 AC 80 ms
71,652 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict

class UnionFind():

    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.rank = [0]*(n+1)

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

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

        if(x == y):
            return
        elif(self.rank[x] > self.rank[y]):
            self.root[x] += self.root[y]
            self.root[y] = x
        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            if(self.rank[x] == self.rank[y]):
                self.rank[y] += 1

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

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

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

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

    def group_members(self):
        group_members = defaultdict(list)
        for member in range(self.n):
            group_members[self.find(member)].append(member)
        return group_members
        
N,Q=map(int,input().split())
P=list(map(int,input().split()))
uf=UnionFind(N)
for i in range(N):
    if P[i]!=-1:
        uf.unite(i+1,P[i])
for i in range(Q):
    a,b=map(int,input().split())
    if uf.same(a,b):
        print('Yes')
    else:
        print('No')
0