Sub topic 13
Union-Find and the Cut Property
Assume you know arrays, trees, graph terminology, and asymptotic notation. This chapter uses an undirected, weighted graph.
Union-find with union by rank and path compression
A disjoint-set union structure, commonly called union-find, maintains a collection of separate sets. It supports two main operations:
find(x)returns the representative, or root, of the set containingx.union(x, y)combines the sets containingxandy.
Each set is stored as a tree. Initially, every vertex is its own root. Two vertices are in the same set exactly when their roots are equal.
Union by rank attaches the shorter tree below the taller tree. Rank is an estimate of tree height. If two roots have equal rank, one becomes the parent of the other and its rank increases by one.
Path compression improves find. After finding a root, it makes every visited vertex point directly to that root. Future searches then become shorter.
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, a, b):
root_a = self.find(a)
root_b = self.find(b)
if root_a == root_b:
return False
if self.rank[root_a] < self.rank[root_b]:
root_a, root_b = root_b, root_a
self.parent[root_b] = root_a
if self.rank[root_a] == self.rank[root_b]:
self.rank[root_a] += 1
return True
uf = UnionFind(5)
uf.union(0, 1)
uf.union(1, 2)
print(uf.find(2) == uf.find(0)) # True
print(uf.union(0, 2)) # False: already connected| Operation | Time with both optimizations |
|---|---|
| `find` or `union` | Amortized O(α(n)) |
Here, α is the inverse Ackermann function. It grows so slowly that it is at most a small constant for all practical input sizes.
Spanning trees and the cut property
A spanning tree of a connected undirected graph contains every vertex, has no cycle, and has exactly V - 1 edges. A minimum spanning tree, or MST, is a spanning tree with the smallest possible total edge weight.
A cut divides the vertices into two nonempty groups. An edge crosses the cut when its endpoints belong to different groups.
The cut property states:
> For any cut, a light edge crossing that cut is safe to include in some MST.
“Light” means that no crossing edge has smaller weight. If several edges tie for the smallest weight, any one of them is safe.
Kruskal’s algorithm uses both ideas. It sorts edges by weight, then uses union-find to accept an edge only when its endpoints are in different components. The cut property justifies each accepted edge. Sorting dominates the running time, giving O(E log E).
Exercise
Edges have weights AB=1, AC=4, BC=2, BD=3, CD=5. Which edges does Kruskal's algorithm select?
Show answer
It selects AB, BC, and BD. Their total weight is 6. Edge AC is rejected because A and C are already connected, and CD is unnecessary.