-
Notifications
You must be signed in to change notification settings - Fork 2
/
Cycle_Detection_in_Undirected_Graph_using_DSU.cpp
94 lines (72 loc) · 1.27 KB
/
Cycle_Detection_in_Undirected_Graph_using_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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <bits/stdc++.h>
using namespace std;
const int n = 1e5+6;
vector<int> parent(n);
vector<int> sz(n);
void make_set(int v)
{
parent[v] = v;
sz[v] = 1;
}
int find_set(int v)
{
if(v == parent[v])
{
return v;
}
return parent[v] = find_set(parent[v]);
}
void union_sets(int a, int b)
{
a = find_set(a);
b = find_set(b);
if(a != b)
{
if(sz[a]<sz[b])
{
swap(a,b);
}
parent[b] = a;
sz[a] += sz[b];
}
}
int main()
{
for(int i=0; i<n; i++)
{
make_set(i);
}
int n,m;
cin>>n>>m;
vector<vector<int>> edges;
for(int i=0; i<m; i++)
{
int u, v;
cin>>u>>v;
edges.push_back({u,v});
}
bool cycle = false;
for(auto x : edges)
{
int u = x[0];
int v = x[1];
int k = find_set(u);
int l = find_set(v);
if(k == l)
{
cycle = true;
break;
}
else{
union_sets(u,v);
}
}
if(cycle)
{
cout<<"Yes, there is a Cycle!\n";
}
else{
cout<<"No, Cycle wasn't found!\n";
}
return 0;
}