forked from starrohan999/Hacktoberfest-Accepted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDisjointSet.java
94 lines (65 loc) · 1.93 KB
/
DisjointSet.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package disjoint_set;
import java.util.Scanner;
//----------------------------------------------GYAAN-----------------------------------------------------------//
// -> Disjoint set data structure is used to find loop in the graph;
// -> It has two methods Union() and Parent()
// -> Union() is used to combine two elements and make single parent of them
// -> Parent() is used to find the parent of given element
//--------------------------------------------------------------------------------------------------------------//
class DisJoint_Set{
int[] parent = new int[100];
int[] rank = new int[100];
void MakeSet()
{
for( int i = 0; i < 100; i++)
{
parent[i] = i;
rank[i] = 0;
}
}
int FindParent(int node)
{
if(node == parent[node]) return node;
// return FindParent(parent[node]); // this will return parent but will not perform path compression
return parent[node] = FindParent(parent[node]); // for path compression
}
void union(int src, int dest)
{
int u = FindParent(src);
int v = FindParent(dest);
System.out.println("Parent of src is " + u + "Parent of dest is " + v );
if(rank[u] < rank[v])
{
parent[u] = v;
}
else if(rank[v] < rank[u])
{
parent[v] = u;
}
else {
parent[u] = v;
rank[v]++;
}
}
}
public class DisjointSet {
public static void main(String[] args) {
DisJoint_Set d = new DisJoint_Set();
d.MakeSet();
Scanner s = new Scanner(System.in);
int m = s.nextInt();
while(m > 0)
{
int src = s.nextInt();
int dest = s.nextInt();
d.union(src, dest);
m--;
}
System.out.println("ENter nodes to match their parents");
int a = s.nextInt();
int b= s.nextInt();
System.out.println("Parent of a is " + d.FindParent(a));
System.out.println("Parent of b is " + d.FindParent(b));
s.close();
}
}