-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathUnionFind.java
More file actions
49 lines (41 loc) · 980 Bytes
/
UnionFind.java
File metadata and controls
49 lines (41 loc) · 980 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
package com.example;
/**
* Created by huangxk on 2016/12/10.
*/
public class UnionFind {
int[] id;
int[] treeSize;
int count;
public UnionFind(int N) {
id = new int[N];
treeSize = new int[N];
count = N;
for (int i = 0; i < N; i++) {
id[i] = i;
treeSize[i] = 1;
}
}
public int getCount() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int find(int p) {
if (p != id[p]) p = id[p];
return p;
}
public void union(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) return;
if (treeSize[pRoot] < treeSize[qRoot]) {
id[pRoot] = qRoot;
treeSize[qRoot] += treeSize[pRoot];
} else {
id[qRoot] = pRoot;
treeSize[pRoot] += treeSize[qRoot];
}
count--;
}
}