-
Notifications
You must be signed in to change notification settings - Fork 0
/
DisjSets.java
44 lines (36 loc) · 944 Bytes
/
DisjSets.java
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
package org.gra4j.trochilus;
public class DisjSets {
private int[] s;
public DisjSets (int numElements) {
if (numElements < 0) {
throw new IllegalArgumentException("Illegal Capacity: "+numElements);
}
s = new int[numElements];
for (int i = 0; i < s.length; i++)
s[i] = -1;
}
public void union (int root1, int root2) {
s[root2] = root1;
}
public void deepUnion (int root1, int root2) {
if (s[root2] < s[root1])
s[root1] = root2;
else {
if (s[root1] == s[root2])
s[root1]--;
s[root2] = root1;
}
}
public int find (int x) {
if (s[x] < 0)
return x;
else
return find(s[x]);
}
public int compressFind (int x) {
if (s[x] < 0)
return x;
else
return s[x] = compressFind(s[x]);
}
}