forked from hariom20singh/data-structure-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisjoint_Set.cpp
More file actions
83 lines (68 loc) · 1.26 KB
/
Disjoint_Set.cpp
File metadata and controls
83 lines (68 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <bits/stdc++.h>
using namespace std;
class DisjSet {
int *rank, *parent, n;
public:
DisjSet(int n){
rank = new int[n];
parent = new int[n];
this->n = n;
makeSet();
}
void makeSet(){
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i]=0;
}
}
int findPar(int x){
if (parent[x] == x){
return x;
}
return parent[x]=findPar(parent[x]);//path compression
}
// Do union of two sets represented
// by x and y.
void Union(int x, int y)
{
// Find current sets of x and y
int xset = findPar(x);
int yset = findPar(y);
// If they are already in same set
if (xset == yset)
return;
// Put smaller ranked item under
// bigger ranked item if ranks are
// different
if (rank[xset] < rank[yset]) {
parent[xset] = yset;
}
else if (rank[xset] > rank[yset]) {
parent[yset] = xset;
}
// If ranks are same, then increment
// rank.
else {
parent[yset] = xset;
rank[xset] = rank[xset] + 1;
}
}
};
// Driver Code
int main()
{
// Function Call
DisjSet obj(5);
obj.Union(0, 2);
obj.Union(4, 2);
obj.Union(3, 1);
if (obj.findPar(4) == obj.findPar(0))
cout << "Belong to diff\n";
else
cout << "No\n";
if (obj.findPar(1) == obj.findPar(0))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}