-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementDisjointSet.java
More file actions
86 lines (69 loc) · 2.23 KB
/
ImplementDisjointSet.java
File metadata and controls
86 lines (69 loc) · 2.23 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
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.Scanner;
public class ImplementDisjointSet {
public static void main(String[] args) {
// 创建并查集附象
DisjointSet uf = new DisjointSet(5);
System.out.println("默认情况下,并查集中有:" + uf.count() + "个分组");
// 从控制台录人两个要合并的元素,调用union方法合并,观察合并后并查集中的分组是否威少
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入第一个要合并的元素:");
int p = sc.nextInt();
System.out.println("请输入第二个要合并的元素:");
int q = sc.nextInt();
if (q >= 5 || p >= 5) {
sc.close();
break;
}
// 判断这两个元素是否已经在同一组了
if (uf.connected(p, q)) {
System.out.println(p + "元素和" + p + "元素已经在同一个组中了");
continue;
} else {
uf.union(p, q);
System.out.println("当前并查集中还有:" + uf.count() + "个分组");
}
}
}
}
class DisjointSet {
private int count;
private int[] parent;
private int[] rank;
DisjointSet(int N) {
this.count = N;
this.parent = new int[N];
this.rank = new int[N];
for (int i = 0; i < N; i++) {
this.parent[i] = i;
this.rank[i] = 1;
}
}
int count() {
return this.count;
}
int find(int p) {
while (parent[p] != p) {
p = parent[p];
}
return p;
}
boolean connected(int p, int q) {
return find(p) == find(q);
}
void union(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (qRoot == pRoot) {
return;
}
if (rank[pRoot] < rank[qRoot]) {
parent[pRoot] = qRoot;
rank[qRoot] = rank[pRoot] + 1 <= rank[qRoot] ? rank[qRoot] : rank[pRoot] + 1;
} else {
parent[qRoot] = pRoot;
rank[pRoot] = rank[qRoot] + 1 <= rank[pRoot] ? rank[pRoot] : rank[qRoot] + 1;
}
this.count--;
}
}