-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisjoint.cpp
80 lines (75 loc) · 1.47 KB
/
disjoint.cpp
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
#include <bits/stdc++.h>
#include <algorithm>
//Disjoint Sets using union by rank and path compression Graph Algorithm
using namespace std;
class DisjointSet
{
private:
void MakeSet(int n);
public:
typedef struct Node
{
int data;
int rank;
struct Node* parent;
}N;
vector<N*> map; //uses to find Node from data
DisjointSet(int n);
void Union(int a , int b);
N* FindSet(N* );
void display();
};
/*
* n: number of nodes in graph
*/
DisjointSet::DisjointSet(int n)
{
for (int i=0; i<n; ++i)
MakeSet(i);
}
void DisjointSet::MakeSet(int node)
{
N *n = new N();
n->data = node;
n->rank =0;
n->parent = n;
map.push_back(n);
}
DisjointSet::N* DisjointSet::FindSet(N* n)
{
if(n->data == n->parent->data)
return n;
FindSet(n->parent);
}
void DisjointSet::Union(int a , int b)
{
N* pa = FindSet(map[a]); //Find parent
map[a]->parent = pa; //path compression
N *pb = FindSet(map[b]);
map[b]->parent = pb; //path compression
if(pa->rank == pb->rank) // same rank , choose any one)
{
++pa->rank; // a parent
pb->parent = pa;
}
else if(pa->rank >= pb->rank)
pb->parent =pa;
else
pa->parent = pb;
}
void DisjointSet::display()
{
for (int i=0; i<map.size(); i++)
cout << i << "--->"<< FindSet(map[i])->data<<endl;
}
int main(int argc, char* argv[])
{
DisjointSet d(7);
d.Union(0, 1);
d.Union(1, 2);
d.Union(3, 4);
d.Union(5, 6);
d.Union(4, 5);
d.Union(2, 6);
d.display();
}