-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathunionFindDS.java
More file actions
62 lines (54 loc) · 1.26 KB
/
Copy pathunionFindDS.java
File metadata and controls
62 lines (54 loc) · 1.26 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
50
51
52
53
54
55
56
57
58
59
60
61
62
package DATA_STRUCTURE;
public class unionFindDS {
//Union Find DataStructure
//Disjoint set
static int n = 6;
static int [] parent = new int[n];
static int [] rank = new int[n];
static void makeSet(){
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
rank[i]=0;
}
}
static int FIND(int x){
if(parent[x]==x){
return x;
}
else{
return parent[x] = FIND(parent[x]);
}
}
static void Union(int x,int y){
x = FIND(x);
y = FIND(y);
if(x == y){
return;
}
if(rank[x]<rank[y]){
parent[x] = y;
}
else if(rank[y]<rank[x]){
parent[y] = x;
}else{
parent[y] =x;
rank[x]++;
return;
}
}
public static void main(String[] args) {
makeSet();
Union(0, 3);
Union(3, 5);
Union(1, 2);
if (FIND(5) == FIND(0))
System.out.println("Yes");
else
System.out.println("No");
// Check if 1 is a friend of 0
if (FIND(1) == FIND(0))
System.out.println("Yes");
else
System.out.println("No");
}
}