Skip to content

Commit 11a45d9

Browse files
authored
Merge pull request #418 from ishaanmehta4/patch-1
Create disjointSet.cpp
2 parents 61a3bc5 + ff639b7 commit 11a45d9

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

18. Graph/disjointSet.cpp

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// disjoin set
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
class DisjointSet
6+
{
7+
int *parent, *rank;
8+
9+
public:
10+
DisjointSet(int n /* no. of nodes*/)
11+
{
12+
parent = new int[n];
13+
rank = new int[n];
14+
15+
for (int i = 0; i < n; i++)
16+
parent[i] = i, rank[i] = 0;
17+
}
18+
19+
int findParent(int node)
20+
{
21+
if (parent[node] == node)
22+
return node;
23+
24+
return parent[node] = findParent(parent[node]);
25+
}
26+
27+
int makeUnion(int node1, int node2)
28+
{
29+
int parent2 = findParent(node2);
30+
int parent1 = findParent(node1);
31+
32+
if (rank[parent1] > rank[parent2])
33+
{
34+
parent[parent2] = parent1;
35+
}
36+
else if (rank[parent1] < rank[parent2])
37+
{
38+
parent[parent1] = parent2;
39+
}
40+
else
41+
{
42+
rank[parent1]++;
43+
parent[parent2] = parent1;
44+
}
45+
}
46+
};
47+
48+
int main() {
49+
DisjointSet ds(5);
50+
ds.makeUnion(0,4);
51+
ds.makeUnion(0,1);
52+
ds.makeUnion(2,3);
53+
54+
cout<<ds.findParent(2)<<" "<<ds.findParent(4)<<endl;
55+
56+
ds.makeUnion(1,3);
57+
cout<<ds.findParent(2);
58+
59+
}

0 commit comments

Comments
 (0)