-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdsu_cycle_detection_undireted_graph.cpp
More file actions
66 lines (53 loc) · 1.08 KB
/
dsu_cycle_detection_undireted_graph.cpp
File metadata and controls
66 lines (53 loc) · 1.08 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
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 6;
vector<int> parent(N);
vector<int> size(N);
void makeSet(int v) {
parent[v] = v;
size[v] = 1;
}
int findSet(int v) {
if(v == parent[v])
return v;
return parent[v] = findSet(parent[v]);
}
void unionSet(int a, int b) {
a = findSet(a);
b = findSet(b);
if(a != b) {
if(size[a] < size[b])
swap(a, b);
parent[b] = a;
size[a] += size[b];
}
}
int main() {
for(int i=0; i<N; i++) {
makeSet(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 i: edges) {
int u = i[0];
int v = i[1];
int x = findSet(u);
int y = findSet(v);
if(x == y)
cycle = true;
else
unionSet(u, v);
}
if(cycle)
cout<<"Cycle is present in the above graph";
else
cout<<"No cycle prsent in the given graph";
return 0;
}