forked from pphdsny/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisjointSet.java
More file actions
50 lines (44 loc) · 952 Bytes
/
Copy pathDisjointSet.java
File metadata and controls
50 lines (44 loc) · 952 Bytes
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
package pp.arithmetic.model;
/**
* Created by wangpeng on 2018/9/29.
* 并查集实现
*/
public class DisjointSet {
private int count = 0;
private int[] id;
private int[] size;
public DisjointSet(int n) {
id = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
id[i] = i;
size[i] = 1;
}
count = n;
}
public int find(int n) {
while (n != id[n]) {
id[n] = id[id[n]];
n = id[n];
}
return n;
}
public void union(int p, int q) {
int _p = find(p);
int _q = find(q);
if (_p == _q) {
return;
}
if (size[_p] > size[_q]) {
id[_q] = _p;
size[_p] += size[_q];
} else {
id[_p] = _q;
size[_q] += size[_p];
}
count--;
}
public int count() {
return count;
}
}