-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUnionFindTree.py
More file actions
58 lines (39 loc) · 1.11 KB
/
UnionFindTree.py
File metadata and controls
58 lines (39 loc) · 1.11 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class UnionFind:
def __init__(self, n: int) -> None:
self.n = n
self.p = [-1] * n
def leader(self, a: int) -> int:
while self.p[a] >= 0:
a = self.p[a]
return a
def merge(self, a: int, b: int) -> int:
x = self.leader(a)
y = self.leader(b)
if x == y:
return x
if self.p[x] > self.p[y]:
x, y = y, x
self.p[x] += self.p[y]
self.p[y] = x
return x
def same(self, a: int, b: int) -> bool:
return self.leader(a) == self.leader(b)
def groups(self) -> list:
member = [[] for _ in range(self.n)]
for i in range(self.n):
member[self.leader(i)].append(i)
return member
def size(self, a: int) -> int:
return -self.p[self.leader(a)]
def main() -> None:
N, M = map(int, input().split())
UF = UnionFind(N)
for _ in range(m):
A, B = map(lambda x: int(x) - 1,input().split())
UF.merge(A, B)
ans = 0
for i in range(N):
ans = max(ans, UF.size(i))
print(ans)
if __name__ == "__main__":
main()