結果

問題 No.2316 Freight Train
ユーザー flygon
提出日時 2023-05-26 21:25:06
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 490 ms / 2,000 ms
コード長 1,260 bytes
コンパイル時間 139 ms
コンパイル使用メモリ 82,556 KB
実行使用メモリ 106,752 KB
最終ジャッジ日時 2024-12-25 04:37:42
合計ジャッジ時間 11,325 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(5*10**5)
input = sys.stdin.readline
from collections import defaultdict, deque, Counter
from heapq import heappop, heappush
from bisect import bisect_left, bisect_right
from math import gcd
from collections import defaultdict


class UnionFind:
    def __init__(self, n):
        self.n = n
        self.p = [-1] * (n+1)

    def find(self, x):
        if self.p[x] < 0:
            return x
        else:
            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 same(self, a, b):
        return self.find(a) == self.find(b)

    def group(self):
        d = defaultdict(list)
        for i in range(1, self.n+1):
            par = self.find(i)
            d[par].append(i)
        return d

n,q = map(int,input().split())

uf = UnionFind(n)
p = list(map(int,input().split()))
for i in range(n):
    if p[i] == -1: continue
    uf.union(i+1, p[i])

for i in range(q):
    a,b = map(int,input().split())
    if uf.same(a,b):
        print('Yes')
    else:
        print('No')
0