-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.test.py
44 lines (36 loc) · 1.07 KB
/
example.test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# verification-helper: PROBLEM https://judge.yosupo.jp/problem/unionfind
import sys
input = sys.stdin.buffer.readline
class UnionFindTree:
def __init__(self, n):
self.par = list(range(n)) # parent
self.rank = [0] * n # depth of tree
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def unite(self, x, y):
x, y = self.find(x), self.find(y)
if x == y:
return
if self.rank[x] < self.rank[y]:
self.par[x] = y
else:
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def is_same(self, x, y):
return self.find(x) == self.find(y)
def main() -> None:
N, Q = map(int, input().split())
uft = UnionFindTree(N)
for _ in range(Q):
t, u, v = map(int, input().split())
if t == 0:
uft.unite(u, v)
else:
print(int(uft.is_same(u, v)))
if __name__ == "__main__":
main()