結果

問題 No.2316 Freight Train
ユーザー yupoohyupooh
提出日時 2023-05-26 21:26:06
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 518 ms / 2,000 ms
コード長 1,589 bytes
コンパイル時間 1,266 ms
コンパイル使用メモリ 86,692 KB
実行使用メモリ 106,284 KB
最終ジャッジ日時 2023-08-26 10:07:15
合計ジャッジ時間 14,388 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 79 ms
71,580 KB
testcase_01 AC 81 ms
71,524 KB
testcase_02 AC 80 ms
71,392 KB
testcase_03 AC 499 ms
105,608 KB
testcase_04 AC 381 ms
89,892 KB
testcase_05 AC 376 ms
89,716 KB
testcase_06 AC 226 ms
80,612 KB
testcase_07 AC 361 ms
83,016 KB
testcase_08 AC 472 ms
106,080 KB
testcase_09 AC 426 ms
95,632 KB
testcase_10 AC 421 ms
89,844 KB
testcase_11 AC 459 ms
102,812 KB
testcase_12 AC 464 ms
99,944 KB
testcase_13 AC 518 ms
105,820 KB
testcase_14 AC 508 ms
105,828 KB
testcase_15 AC 492 ms
106,048 KB
testcase_16 AC 494 ms
105,832 KB
testcase_17 AC 502 ms
106,064 KB
testcase_18 AC 511 ms
106,284 KB
testcase_19 AC 509 ms
105,964 KB
testcase_20 AC 497 ms
105,784 KB
testcase_21 AC 481 ms
105,872 KB
testcase_22 AC 493 ms
106,068 KB
testcase_23 AC 187 ms
104,516 KB
testcase_24 AC 199 ms
105,776 KB
testcase_25 AC 192 ms
105,132 KB
testcase_26 AC 174 ms
105,196 KB
testcase_27 AC 137 ms
77,884 KB
testcase_28 AC 84 ms
71,652 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline
n,q=map(int,input().split())
p=list(map(int,input().split()))
from collections import defaultdict

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

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def all_group_members(self):
        group_members = defaultdict(list)
        for member in range(self.n):
            group_members[self.find(member)].append(member)
        return group_members

    def __str__(self):
        return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())
uf=UnionFind(n)
for i in range(n):
  if p[i]==-1:
    continue
  uf.union(p[i]-1,i)
for _ in range(q):
  a,b=map(int,input().split())
  if uf.same(a-1,b-1):
    print("Yes")
  else:
    print("No")
0