The union-find structure (or disjoint sets) answers two questions very fast: “are these two elements in the same group?” and “merge the groups of these two”. Each group is a tree whose root identifies it.
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.groups = n
def root(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path compression
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.root(a), self.root(b)
if ra == rb:
return False # they were already together
self.parent[ra] = rb
self.groups -= 1
return True
uf = UnionFind(5)
print(uf.union(0, 1), uf.union(1, 2), uf.union(0, 2)) # True True False
print(uf.groups) # 3
def kruskal(n, edges): # edges: (weight, u, v)
uf = UnionFind(n)
total = 0
for weight, u, v in sorted(edges):
if uf.union(u, v): # only if it does not close a cycle
total += weight
return total if uf.groups == 1 else None
print(kruskal(4, [(1, 0, 1), (2, 1, 2), (3, 0, 2), (4, 2, 3)])) # 7
- Path compression (
parent[x] = parent[parent[x]]) flattens the tree and makes each operation cost almost O(1). unionreturnsFalseif the two elements were already together: joining them would close a cycle.- Kruskal: sort the edges by weight and keep each one that does not close a cycle. At the end there is a single group if the graph is connected, with n − 1 edges.
- It also serves to count connected components while edges are added, as in the exercise on merging groups.
You practice it in Merging groups and Minimum spanning tree.