結果

問題 No.2316 Freight Train
ユーザー miya145592miya145592
提出日時 2023-05-26 21:53:38
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 872 ms / 2,000 ms
コード長 1,541 bytes
コンパイル時間 726 ms
コンパイル使用メモリ 87,056 KB
実行使用メモリ 115,680 KB
最終ジャッジ日時 2023-08-26 11:19:48
合計ジャッジ時間 20,643 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 74 ms
71,148 KB
testcase_01 AC 75 ms
71,468 KB
testcase_02 AC 75 ms
71,148 KB
testcase_03 AC 838 ms
113,576 KB
testcase_04 AC 615 ms
101,872 KB
testcase_05 AC 573 ms
96,508 KB
testcase_06 AC 289 ms
84,092 KB
testcase_07 AC 569 ms
104,576 KB
testcase_08 AC 736 ms
107,556 KB
testcase_09 AC 714 ms
107,156 KB
testcase_10 AC 687 ms
106,188 KB
testcase_11 AC 755 ms
105,832 KB
testcase_12 AC 768 ms
110,568 KB
testcase_13 AC 852 ms
114,592 KB
testcase_14 AC 872 ms
115,264 KB
testcase_15 AC 867 ms
113,616 KB
testcase_16 AC 853 ms
114,280 KB
testcase_17 AC 849 ms
114,856 KB
testcase_18 AC 849 ms
114,656 KB
testcase_19 AC 851 ms
115,220 KB
testcase_20 AC 842 ms
115,680 KB
testcase_21 AC 842 ms
115,308 KB
testcase_22 AC 818 ms
115,316 KB
testcase_23 AC 322 ms
108,504 KB
testcase_24 AC 336 ms
108,660 KB
testcase_25 AC 327 ms
108,456 KB
testcase_26 AC 310 ms
108,396 KB
testcase_27 AC 278 ms
98,256 KB
testcase_28 AC 73 ms
71,628 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, n, w=None):
        self.par = [-1]*n
        self.rank = [0]*n
        self.siz = [1]*n
        self.cnt = n
        self.min_node = [i for i in range(n)]
        self.weight = w if w else [1]*n

    def root(self, x):
        if self.par[x] == -1:
            return x
        self.par[x] = self.root(self.par[x])
        return self.par[x]

    def issame(self, x, y):
        return self.root(x) == self.root(y)
            
    def unite(self, x, y):
        px = self.root(x)
        py = self.root(y)
        if px == py:
            return False
        if self.rank[px] < self.rank[py]:
            px, py = py, px
        self.par[py] = px
        if self.rank[px] == self.rank[py]:
            self.rank[px] += 1
        self.siz[px] += self.siz[py]
        self.cnt -= 1
        self.min_node[px] = min(self.min_node[px], self.min_node[py])
        self.weight[px] += self.weight[py]
        return False

    def count(self):
        return self.cnt

    def min(self, x):
        return self.min_node[self.root(x)]

    def getweight(self, x):
        return self.weight[self.root(x)]
    
    def size(self, x):
        return self.siz[self.root(x)]

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)
for i, p in enumerate(P):
    p-=1
    if p<0:
        continue
    UF.unite(i, p)
for a, b in AB:
    a-=1
    b-=1
    if UF.issame(a, b):
        print("Yes")
    else:
        print("No")
0