結果

問題 No.2316 Freight Train
ユーザー gr1msl3ygr1msl3y
提出日時 2023-05-28 00:50:48
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 658 ms / 2,000 ms
コード長 1,184 bytes
コンパイル時間 593 ms
コンパイル使用メモリ 87,036 KB
実行使用メモリ 129,620 KB
最終ジャッジ日時 2023-08-27 01:50:09
合計ジャッジ時間 15,567 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 68 ms
71,280 KB
testcase_01 AC 68 ms
71,392 KB
testcase_02 AC 67 ms
71,292 KB
testcase_03 AC 658 ms
128,152 KB
testcase_04 AC 436 ms
107,064 KB
testcase_05 AC 392 ms
99,120 KB
testcase_06 AC 216 ms
84,340 KB
testcase_07 AC 445 ms
123,668 KB
testcase_08 AC 487 ms
109,020 KB
testcase_09 AC 491 ms
116,764 KB
testcase_10 AC 490 ms
115,600 KB
testcase_11 AC 531 ms
112,384 KB
testcase_12 AC 561 ms
122,444 KB
testcase_13 AC 605 ms
128,496 KB
testcase_14 AC 618 ms
125,352 KB
testcase_15 AC 585 ms
129,532 KB
testcase_16 AC 593 ms
128,920 KB
testcase_17 AC 589 ms
129,172 KB
testcase_18 AC 599 ms
128,288 KB
testcase_19 AC 604 ms
129,620 KB
testcase_20 AC 608 ms
128,816 KB
testcase_21 AC 584 ms
127,900 KB
testcase_22 AC 611 ms
129,368 KB
testcase_23 AC 291 ms
121,488 KB
testcase_24 AC 308 ms
121,432 KB
testcase_25 AC 294 ms
121,540 KB
testcase_26 AC 287 ms
121,568 KB
testcase_27 AC 267 ms
116,404 KB
testcase_28 AC 63 ms
71,360 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1]*n
        self.rank = [0]*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 issame(self, x, y):
        return self.find(x) == self.find(y)

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1

    def root(self):
        return [i for i in range(self.n) if self.parents[i] < 0]


N, Q = map(int, input().split())
P = [-1]+list(map(int, input().split()))
query = [list(map(int, input().split())) for _ in range(Q)]
state = UnionFind(N+1)
for i, p in enumerate(P):
    if p != -1:
        state.union(i, p)
ans = []
for a, b in query:
    ans.append('Yes' if state.issame(a, b) else 'No')

print(*ans, sep='\n')
0