-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion_find.py
More file actions
34 lines (26 loc) · 769 Bytes
/
union_find.py
File metadata and controls
34 lines (26 loc) · 769 Bytes
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
"""Simple Union Find (with path compression) datastructure implementation for
use in MST.
"""
class Unionfind:
def __init__(self, size):
self._roots = list(range(size))
self._rank = [0 for _ in range(size)]
def __getitem__(self, elt):
root = elt
while root != self._roots[root]:
root = self._roots[root]
# path compression
while elt != root:
parent = self._roots[elt]
self._roots[elt] = root
elt = parent
return root
def is_connected(self, a, b):
return self[a] == self[b]
def union(self, p, q):
r1 = self[p]
r2 = self[q]
if r1 == r2:
return False
self._roots[r1] = r2
return True