Templates
Template: 14. UNION-FIND (Disjoint Set)
Mark when done:
14. UNION-FIND (Disjoint Set)
# =============================================================================
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
self.components = n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # path compression
return self.parent[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px == py:
return False # already connected
if self.rank[px] < self.rank[py]:
px, py = py, px
self.parent[py] = px # union by rank
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
self.components -= 1
return True
# =============================================================================