結果

問題 No.2316 Freight Train
ユーザー cozy_sauna
提出日時 2023-05-30 23:56:16
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 889 ms / 2,000 ms
コード長 1,351 bytes
コンパイル時間 954 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 108,116 KB
最終ジャッジ日時 2024-12-28 13:21:55
合計ジャッジ時間 21,269 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

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