Union Find

问题描述

union find:并查集
有一组点的集合${a_1,a_2,…a_n}$,定义一种连接关系,如果$a_i$连接$a_j$,则:

  • 自反性:$a_i$连接$a_i$
  • 对称性:$a_j$也连接$a_i$
  • 传递性:如果$a_j$连接$a_k$,则$a_i$也连接$a_k$
    对于上面的集合我们想实现基本的操作,包括元素的初始化,连接两个元素,找到某个元素连接的元素,判断两个元素是否连接等。具体API如下:
    img1

具体实现

可以用一维数组表示元素集合,数组下标表示元素位置,数组值表示当前元素所连接至的元素。具体实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class UF {

private int[] parent; // parent[i] = parent of i
private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
private int count; // number of components

public UF(int N) {
if (N < 0) throw new IllegalArgumentException();
count = N;
parent = 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;

// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
}

// validate that p is a valid index
private void validate(int p) {
int N = parent.length;
if (p < 0 || p >= N) {
throw new IndexOutOfBoundsException("index " + p + " is not between 0 and " + (N-1));
}
}

/**
* Reads in a an integer <tt>N</tt> and a sequence of pairs of integers
* (between <tt>0</tt> and <tt>N-1</tt>) from standard input, where each integer
* in the pair represents some site;
* if the sites are in different components, merge the two components
* and print the pair to standard output.
*/
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.connected(p, q)) continue;
uf.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count() + " components");
}
}

采用的算法是 Weghted Quick-Union With Path Compression,对一般的 quick-union 算法做了两个改进:

  • union 方法实现中,两个连通子集连接时,将根据子集树的深度来连接
  • find 方法实现中,顺便压缩了子集树的深度
    这样做后union 和 find 方法的算法复杂度下降到接近于 1。
    具体细节见算法(第四版)的 1.5节。