-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunionfind.py
More file actions
30 lines (23 loc) · 832 Bytes
/
Copy pathunionfind.py
File metadata and controls
30 lines (23 loc) · 832 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
from mypy.checkexpr import defaultdict
class UnionFind:
def __init__(self, elements):
self.parents = {e: e for e in elements}
self.ranks = {e: 1 for e in elements}
self.size = len(elements)
def find(self, x):
while self.parents[x] != x:
x, self.parents[x] = self.parents[x], self.parents[self.parents[x]]
return x
def union(self, x1, x2):
x1 = self.find(x1)
x2 = self.find(x2)
if x1 == x2: return
if self.ranks[x1] < self.ranks[x2]: x1, x2 = x2, x1
self.parents[x2] = x1
if self.ranks[x1] == self.ranks[x2]: self.ranks[x1] += 1
self.size -= 1
def to_sets(self):
results = defaultdict(set)
for e in self.parents:
results[self.find(e)].add(e)
return results.values()