From 0bbfbb60c1b6b3c060d464be0acb848be87e006e Mon Sep 17 00:00:00 2001 From: perfectdash <116922021+perfectdash@users.noreply.github.com> Date: Sat, 28 Oct 2023 11:14:29 +0530 Subject: [PATCH] Added Cycle_detection_using_DSU.cpp Cycle_detection_using_DSU --- Coding/C++/Cycle_detection_using_D.cpp | 83 ++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Coding/C++/Cycle_detection_using_D.cpp diff --git a/Coding/C++/Cycle_detection_using_D.cpp b/Coding/C++/Cycle_detection_using_D.cpp new file mode 100644 index 00000000..0eed7c7a --- /dev/null +++ b/Coding/C++/Cycle_detection_using_D.cpp @@ -0,0 +1,83 @@ +#include +using namespace std; + +using ll = long long ; + +// DSU -> cycle detection in unidirected graphs (krukshal algorithm) +// implementing a data structure that will operate over disjoint sets +// main focus will be on union and find functions +// intial complexity = O(n) ; +// final after some optimisations =O(1); + +// path compression optimisation -->find function +// union by rank optimisation ---->union function + +class graph{ + ll V; + list > l; + public : + graph(ll V){ + this->V=V; + } + + void merge(ll u,ll v){ + l.push_back(make_pair(u,v)); + } + + ll leader(ll i,vector& parent){ + if(parent[i]==-1){ + return i; + } + return parent[i]=leader(parent[i],parent); + } + + void union_set(ll x,ll y,vector& parent){ + ll s1 = leader(x,parent); + ll s2 = leader(y,parent); + if(s1!=s2){ + parent[s2]=s1; + } + } + + bool cycle_detection(){ + vector parent(V); + for(int i=0;i>t; + while(t--){ + ll n;cin>>n; + graph p(n);ll flag=1; + vector cnt(n); + for(int i=0;i>a>>b; + a--; b--; + p.merge(a,b); + cnt[a]++; cnt[b]++; + if(cnt[a]>=3|| cnt[b]>=3){ + flag=0; + + } + } + } +} +