-
Notifications
You must be signed in to change notification settings - Fork 0
/
union_find_rank_compression.cpp
121 lines (98 loc) · 2.16 KB
/
union_find_rank_compression.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Subset
{
int parent;
int rank;
};
namespace UnionFind
{
int find(struct Subset subsets[],int i);
void Union(struct Subset subsets[],int x,int y);
}
namespace UnionFind
{
int find(struct Subset subsets[],int i)
{
if(subsets[i].parent != i)
subsets[i].parent = find(subsets,subsets[i].parent); //path compression will make every node in the
//path directly attached to its parent.
return subsets[i].parent;
}
void Union(struct Subset subsets[],int x, int y)
{
int xset = UnionFind::find(subsets,x);
int yset = UnionFind::find(subsets,y);
if(subsets[xset].rank < subsets[yset].rank)
subsets[xset].parent = yset;
else if (subsets[xset].rank > subsets[yset].rank)
subsets[yset].parent = xset;
else
{
subsets[yset].parent = xset;
subsets[xset].rank++;
}
}
}
struct Edge
{
int src;
int dst;
};
class Graph
{
int V;
int E;
vector<struct Edge> e;
public:
Graph(int V,int E);
void addEdge(int src,int dst);
bool isCycle();
};
Graph::Graph(int V,int E)
{
this->V = V;
this->E = E;
this->e.clear();
}
void Graph::addEdge(int src,int dst)
{
Edge ee;
ee.src = src;
ee.dst = dst;
this->e.push_back(ee);
}
bool Graph::isCycle()
{
struct Subset* subsets = new struct Subset[this->V];
for (int v = 0; v < this->V; v++)
{
subsets[v].parent = v;
subsets[v].rank = 1;
}
for(int i = 0 ; i < this->E ; i++)
{
int x = UnionFind::find(subsets,this->e[i].src);
int y = UnionFind::find(subsets,this->e[i].dst);
if(x == y)
return true;
UnionFind::Union(subsets, x , y);
}
return false;
}
int main()
{
int V = 3 , E = 3;
Graph g(V,E);
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(0,2);
if(g.isCycle())
cout << "yes" << endl;
else
cout << "no" << endl;
return 0;
}