-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdsu.cpp
77 lines (57 loc) · 1.03 KB
/
dsu.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
//Contains Cycle -- using Disjoint Set Union
#include <bits/stdc++.h>
using namespace std;
class Graph{
int V;
list<pair<int,int> > l;
public:
Graph(int V){
this->V = V;
}
void addEdge(int x, int y){
l.push_back(make_pair(x,y));
}
int findSet(int i, int *parent){
if(parent[i]==-1) return i;
return findSet(parent[i],parent);
}
void union_set(int x, int y, int parent[]){
int s1 = findSet(x,parent);
int s2 = findSet(y,parent);
if(s1!=s2){
parent[s1] = s2;
}
}
bool containsCycle(){
int *parent = new int[V];
for(int i=0;i<V;i++){
parent[i] = -1;
}
for(auto edge:l){
int i = edge.first;
int j = edge.second;
int s1 = findSet(i,parent);
int s2 = findSet(j,parent);
if(s1!=s2){
union_set(s1,s2,parent);
}
else {
cout<<"Contains Cycle"<<endl;
cout<<"Same parents"<<s1<<" "<<s2<<endl;
return true;
}
}
cout<<"Cycle not present"<<endl;
delete[]parent;
return false;
}
};
int main(){
Graph g(4);
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(2,3);
g.addEdge(3,0);
g.containsCycle();
return 0;
}