-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion_find.java
More file actions
35 lines (30 loc) · 788 Bytes
/
union_find.java
File metadata and controls
35 lines (30 loc) · 788 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
public class UnionFind {
private int[] parent;
public UnionFind(int n) {
parent = new int[n];
for (var i = 0; i < n; i++) {
parent[i] = i;
}
}
public int Find(int x) {
if (x == parent[x]) {
return x;
}
// compress the paths
return parent[x] = Find(parent[x]);
}
public void Union(int x, int y) {
var px = Find(x);
var py = Find(y);
if (px != py) {
parent[px] = py;
}
}
public int size() { // number of groups
int ans = 0;
for (int i = 0; i < parent.length(); ++ i) {
if (i == parent[i]) ans ++;
}
return ans;
}
}