并查集

Union-Find

把并查集作为课程中第一个介绍的算法实在是独具匠心。

我现在还记得第一次学到并查集时的惊喜:它像是一篇精彩的短文,读完让人大呼过瘾。其实现是那么的精巧而简洁,以至于在之后在学习 BST,LCT 等复杂晦涩的算法时,我时常会怀念这种 Eureka 的感觉。

Problem Model: Dynamic Connectivity

Given a set of NN objects.

  • Union command: connect two objects.
  • Find/connected query: is there a path connecting the two objects?

Primitive method: Given a unique idid for each connected component.

  • Quick-Find: O(n)O(n) updates the idid as an array. O(1)O(1) query by checking idid.
  • Quick-Union: O(1)O(1) updates the idid as a forest. O(n)O(n) query by checking the idid 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 xx is at most lg⁡N\lg{N}.

Pf. When does depth of xx increase? Increase by 11 when tree T1T_1 containing xx is merged into another tree T2T_2.

  • The size of the tree containing xx at least doubles since ∣T2∣≥∣T1∣|T_2|\geq |T_1|.
  • Size of tree containing xx can double at most lg⁡N\lg N times.

Weighting flattened the tree greatly

Improvement 2: path compression

Just after computing the root of pp, set the idid of each examined node to point of that root.

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");
    }
}
CC BY-NC-SA 4.0
正在加载评论…