-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathUnionFind4.java
More file actions
74 lines (58 loc) · 1.69 KB
/
UnionFind4.java
File metadata and controls
74 lines (58 loc) · 1.69 KB
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
package union_find;
/**
* 基于 rank(深度排名,并不完全表示数的深度) 的优化,比基于 size 的优化要更合理,合并后得到的 h 在某些情况下要更小。
*/
public class UnionFind4 implements UF {
/**
* parent[i] 表示第i个元素所属集合中的根节点。
*/
private int[] parent;
/**
* sz[i] 表示以i为根的集合的深度
*/
private int[] rank;
public UnionFind4(int size) {
parent = new int[size];
rank = new int[size];
// 每一个元素都是一个单独的集合,也是一棵树的根节点,特征为自己指向自己
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
rank[i] = 1;
}
}
@Override
public int getSize() {
return parent.length;
}
private int find(int p) {
if (p < 0 || p >= parent.length) {
throw new IllegalArgumentException("p is out of bound~");
}
// 根节点:parent[p] == p
if (parent[p] != p) {
p = parent[p];
}
return p;
}
@Override
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
@Override
public void unionElements(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) {
return;
}
// 将元素深度低的集合合并到元素深度高的集合上
if (rank[p] < rank[q]) {
parent[pRoot] = qRoot;
} else if (rank[p] > rank[q]){
parent[qRoot] = pRoot;
} else {
parent[qRoot] = pRoot;
rank[pRoot]++;
}
}
}