結果

問題 No.2316 Freight Train
ユーザー cozy_saunacozy_sauna
提出日時 2023-05-30 23:56:16
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 945 ms / 2,000 ms
コード長 1,351 bytes
コンパイル時間 925 ms
コンパイル使用メモリ 86,928 KB
実行使用メモリ 108,996 KB
最終ジャッジ日時 2023-08-28 01:16:37
合計ジャッジ時間 24,821 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 73 ms
71,344 KB
testcase_01 AC 74 ms
71,352 KB
testcase_02 AC 76 ms
71,380 KB
testcase_03 AC 928 ms
108,948 KB
testcase_04 AC 659 ms
91,848 KB
testcase_05 AC 566 ms
91,460 KB
testcase_06 AC 300 ms
79,068 KB
testcase_07 AC 743 ms
83,340 KB
testcase_08 AC 713 ms
108,776 KB
testcase_09 AC 744 ms
96,388 KB
testcase_10 AC 775 ms
91,876 KB
testcase_11 AC 733 ms
105,456 KB
testcase_12 AC 803 ms
101,696 KB
testcase_13 AC 902 ms
108,996 KB
testcase_14 AC 945 ms
108,952 KB
testcase_15 AC 914 ms
108,912 KB
testcase_16 AC 904 ms
108,860 KB
testcase_17 AC 912 ms
108,880 KB
testcase_18 AC 930 ms
108,876 KB
testcase_19 AC 928 ms
108,920 KB
testcase_20 AC 918 ms
108,836 KB
testcase_21 AC 939 ms
108,856 KB
testcase_22 AC 916 ms
108,784 KB
testcase_23 AC 552 ms
108,744 KB
testcase_24 AC 572 ms
108,776 KB
testcase_25 AC 562 ms
106,996 KB
testcase_26 AC 545 ms
106,896 KB
testcase_27 AC 486 ms
78,336 KB
testcase_28 AC 73 ms
71,248 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y: return
        if self.P[x] > self.P[y]: x, y = y, x
        self.P[x] += self.P[y]
        self.P[y] = x

    def size(self, x): return -self.P[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.P) if x < 0]

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

    def group_and_members(self):
        group_info = dict()
        for member in range(self.n): 
            g_id = self.find(member)
            if g_id not in group_info: group_info[g_id] = []
            group_info[g_id].append(member)
        return group_info


N, Q = map(int, input().split())
P = list(map(int, input().split()))
tree = UnionFind(N)
for i in range(N):
    if P[i] == -1: continue
    tree.union(i, P[i] - 1)

for _ in range(Q):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    print("Yes" if tree.same(a, b) else "No")





0