-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion.java
More file actions
45 lines (39 loc) · 997 Bytes
/
Copy pathunion.java
File metadata and controls
45 lines (39 loc) · 997 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
public class union {
static int n = 7;
static int parent[] = new int[n];
static int rank[] = new int[n];
public static void init(){
for(int i=0; i<n; i++){
parent[i] = i;
}
}
public static int find(int x){
if(x == parent[x]){
return x;
}
return parent[x] = find(parent[x]);
}
public static void union(int a, int b){
int parA = find(a);
int parB = find(b);
if(rank[parA] == rank[parB]){
parent[parB] = parA;
rank[parA]++;
} else if(rank[parA] < rank[parB]){
parent[parA] = parB;
} else {
parent[parB] = parA;
}
}
public static void main(String[] args) {
init();
union(1, 3);
System.out.println(find(3));
union(2, 4);
union(3, 6);
union(1, 4);
System.out.println(find(3));
System.out.println(find(4));
union(1, 5);
}
}