并查集
Union-Find
把并查集作为课程中第一个介绍的算法实在是独具匠心。
我现在还记得第一次学到并查集时的惊喜:它像是一篇精彩的短文,读完让人大呼过瘾。其实现是那么的精巧而简洁,以至于在之后在学习 BST,LCT 等复杂晦涩的算法时,我时常会怀念这种 Eureka 的感觉。
Problem Model: Dynamic Connectivity
Given a set of
- Union command: connect two objects.
- Find/connected query: is there a path connecting the two objects?
Primitive method: Given a unique
- Quick-Find:
updates the as an array. query by checking . - Quick-Union:
updates the as a forest. query by checking the of root.
Improvements
Improvement 1: Weighting
- Modify Quick-Union to avoid tall trees.
- Keep track of size of each tree (number of objects).
- Balance by linking the root of smaller tree to the root of larger tree. (Reasonable alternatives: union by height or "rank")
Proposition. Depth of any node
Pf. When does depth of
- The size of the tree containing
at least doubles since . - Size of tree containing
can double at most times.
Improvement 2: path compression
Just after computing the root of
Code Implementation
Weighted quick-union with path compression: in practice, WQUPC is linear.
java
public class UF {
private int[] parent; // parant[i] = parent of i
private byte[] rank; // we apply union by rank here (never more than 31)
private int count; // numbers of connected components
public UF(int n) {
if (n < 0) throw new IllegalArgumentException();
count = n;
parant = new int[n];
rank = new byte[n];
for (int i = 0; i < n; ++i) {
parent[i] = i;
rank[i] = 0;
}
}
public int find(int p) {
validate(p);
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
public int count() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
++rank[rootP];
}
--count;
}
public void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("Index is not between 0 and " + (n-1));
}
}
public static void main(String[] args) {
int n = StdIn.readInt();
UF uf = new UF(n);
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (uf.find(p) == uf.find(q)) continue;
uf.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count() + " components");
}
}
