-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisjointSet.java
More file actions
53 lines (45 loc) · 946 Bytes
/
DisjointSet.java
File metadata and controls
53 lines (45 loc) · 946 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
51
52
53
package hackpack;
public class DisjointSet {
Pair[] disjoint;
int trees;
public DisjointSet(int num){
trees = num;
disjoint = new Pair[num];
for(int i = 0; i < num; i++){
disjoint[i] = new Pair(i,0);
}
}
// Finds parent in lg(n) time
public int find(int node){
while(disjoint[node].value != node){
node = disjoint[node].value;
}
return node;
}
// Joins two disjoint trees together, returns if successful
public boolean union(int a, int b){
int rootA = find(a);
int rootB = find(b); // 2lgn time
if(rootA == rootB){
return false;
}
if(disjoint[rootA].height < disjoint[rootB].height){
disjoint[rootA].value = rootB;
}else{
disjoint[rootB].value = rootA;
if(disjoint[rootA].height == disjoint[rootB].height){
disjoint[rootA].height++;
}
}
trees--;
return true;
}
}
class Pair{
int value;
int height;
public Pair(int v, int h){
value = v;
height = h;
}
}