From 7f0ff584b9f51b9740e98ed8d3a15eab32a9ded4 Mon Sep 17 00:00:00 2001 From: Aayush Vyas <70998175+AayushVyasKIIT@users.noreply.github.com> Date: Fri, 27 Aug 2021 16:07:27 +0530 Subject: [PATCH] Add files via upload # Class Based DSU -Using Path Compression to get the best time complexity O(1) -Using Union Rank to keep track of changes using parent(p) O(logN) --- data_structures/DSU_path_compresssion.cpp | 111 ++++++++++++++++++++++ data_structures/DSU_union_rank.cpp | 58 +++++++++++ 2 files changed, 169 insertions(+) create mode 100644 data_structures/DSU_path_compresssion.cpp create mode 100644 data_structures/DSU_union_rank.cpp diff --git a/data_structures/DSU_path_compresssion.cpp b/data_structures/DSU_path_compresssion.cpp new file mode 100644 index 000000000..e0874e86b --- /dev/null +++ b/data_structures/DSU_path_compresssion.cpp @@ -0,0 +1,111 @@ +#include + +using namespace std; + +#define vi vector + +class DSU{ + private: + vi p,depth,setSize,maxElement,minElement; + public: + DSU(int n){ + p.assign(n,0); + //initially all of them are their parents. + for(int i=0;idepth[y]){ + swap(x,y); + } + //making the shallower root's parent the deeper root + p[x] = y; + + if(depth[x] == depth[y]){ + depth[y]++; + } + //total size of the resultant set. + setSize[y] += setSize[x]; + maxElement[y] = max(maxElement[x],maxElement[y]); + minElement[y] = min(minElement[x],minElement[y]); + } + //checks if both sets equal + + bool isSame(int i,int j){ + if(findSet(i) == findSet(j)){ + return true; + } + return false; + } + void get(int i){ + cout << get_min(i) << " " << get_max(i) << " " <>n;cin>>q; + + DSU d(n+1); + + while(q--){ + string op;cin>>op; + if(op == "union"){ + int i,j; + cin >> i >> j; + d.UnionSet(i,j); + }else{ + int i; + cin >> i; + d.get(i); + } + } + + +} diff --git a/data_structures/DSU_union_rank.cpp b/data_structures/DSU_union_rank.cpp new file mode 100644 index 000000000..535f71ebf --- /dev/null +++ b/data_structures/DSU_union_rank.cpp @@ -0,0 +1,58 @@ +#include + +using namespace std; + +#define vi vector +class DSU{ + private: + vi p,depth,setSize; + public: + DSU(int n){ + p.assign(n,0); + depth.assign(n,0); + setSize.assign(n,0); + for(int i=0;idepth[y]){ + swap(x,y); + } + p[x] = y; + if(depth[x] == depth[y]){ + depth[y]++; + } + setSize[y]+=setSize[x]; + } + bool isSame(int i,int j){ + if(findSet(i) == findSet(j)){ + return true; + } + return false; + } + +}; + +int main(){ + int n;cin>>n; + + DSU d(n+1); + d.unionSet(2,4); + d.unionSet(3,4); + cout << d.findSet(2) <