-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest.java
More file actions
49 lines (41 loc) · 1.23 KB
/
Copy pathTest.java
File metadata and controls
49 lines (41 loc) · 1.23 KB
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
import static java.lang.System.out;
import java.util.Arrays;
public class Test {
// Initialize the disjoint set
static void makeSet(int[] parent) {
Arrays.fill(parent, -1);
}
// Find the representative (root) of the set containing x with path compression
static int find(int x, int[] parent) {
if (parent[x] < 0) {
return x;
} else {
parent[x] = find(parent[x], parent);
return parent[x];
}
}
// Union by rank
static void union(int x, int y, int[] parent) {
int rootX = find(x, parent);
int rootY = find(y, parent);
if (rootX == rootY)
return;
// Union by rank
if (parent[rootX] < parent[rootY]) {
parent[rootX] += parent[rootY];
parent[rootY] = rootX;
} else {
parent[rootY] += parent[rootX];
parent[rootX] = rootY;
}
}
public static void main(String[] args) {
int[] parent = new int[10];
makeSet(parent);
union(1, 2, parent);
union(3, 4, parent);
union(2, 4, parent);
out.println("Parent of 1: " + find(1, parent));
out.println("Parent of 3: " + find(3, parent));
}
}