-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathDisjointSet.java
More file actions
39 lines (32 loc) · 851 Bytes
/
DisjointSet.java
File metadata and controls
39 lines (32 loc) · 851 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
/**
* A.K.A.: Union-Find with Path Compression and Union by Rank
*/
public class DisjointSet {
private int[] parent;
private int[] rank;
public DisjointSet(int v) {
this.parent = new int[v];
for (int i=0; i<v; i++) {
this.parent[i] = i;
}
this.rank = new int[v];
}
public int find(int x) {
if (this.parent[x] != x) {
this.parent[x] = find(this.parent[x]);
}
return this.parent[x];
}
public void union(int x, int y) {
int xx = find(x);
int yy = find(y);
if (this.rank[xx] < this.rank[yy]) {
this.parent[xx] = yy;
} else if (this.rank[xx] > this.rank[yy]) {
this.parent[yy] = xx;
} else {
this.parent[xx] = yy;
this.parent[yy]++;
}
}
}