-
Notifications
You must be signed in to change notification settings - Fork 1
/
UnionFind_v5.java
62 lines (52 loc) · 1.43 KB
/
UnionFind_v5.java
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
/**
* Author : 13152
* Date : 2020/2/9
* Time : 17:53
* Version : 5.0.0
* 路径压缩(降低高度)
* 在查找的过程中,让节点指向它父亲的父亲(爷爷)从而达到降低高度
**/
public class UnionFind_v5 implements UF {
private int[] parent; // 指向父亲的节点
private int[] rank;
public UnionFind_v5(int size) {
parent = new int[size];
rank = new int[size];
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
rank[i] = 1;
}
}
private int findParent(int id) {
if (id < 0 || id >= parent.length)
throw new IllegalArgumentException("id is out of bound");
while (parent[id] != id) {
parent[id] = parent[parent[id]];
id = parent[id];
}
return id;
}
@Override
public int getSize() {
return parent.length;
}
@Override
public boolean isConnect(int p, int q) {
return findParent(p) == findParent(q);
}
@Override
public void unionElements(int p, int q) {
int pRoot = findParent(p);
int qRoot = findParent(q);
if (isConnect(p, q))
return;
if (rank[pRoot] < rank[qRoot])
parent[pRoot] = qRoot;
else if (rank[pRoot] > rank[qRoot])
parent[qRoot] = pRoot;
else{
parent[qRoot] = pRoot;
rank[pRoot]++;
}
}
}