diff --git a/data_structures/dsu_path_compression.cpp b/data_structures/dsu_path_compression.cpp new file mode 100644 index 000000000..4531a6b81 --- /dev/null +++ b/data_structures/dsu_path_compression.cpp @@ -0,0 +1,125 @@ +#include +#include + +using std::cout; +using std::endl; +using std::vector; + +//Disjoint set union +class DSU{ + private: + // p: keeps track of parent of i + // depth: tracks the depth of i + // setSize: size of each chunk(set) + // maxElement : max of each set, using maxElement[representative] + // minElement : min of each set, using minElement[representative] + vector p,depth,setSize,maxElement,minElement; + public: + // parameter : int n -> maximum number of items + explicit DSU(int n){ + p.assign(n,0); + //initially all of them are their own parents. + for(int i=0;i root(representative) + return (p[i] = findSet(p[i])); + } + //union of 2 sets + void UnionSet(int i,int j){ + //check if both belongs to same set or not + if(isSame(i,j)){ + return; + } + + //we find the representative of the i and j + int x = findSet(i); + int y = findSet(j); + + //always keeping the min as x + //shallow tree + if(depth[x]>depth[y]){ + std::swap(x,y); + } + //making the shallower root's parent the deeper root + p[x] = y; + + //if same depth then increase one's depth + if(depth[x] == depth[y]){ + depth[y]++; + } + //total size of the resultant set. + setSize[y] += setSize[x]; + //changing the maximum elements + maxElement[y] = std::max(maxElement[x],maxElement[y]); + minElement[y] = std::min(minElement[x],minElement[y]); + } + //checks if both belongs to same set + bool isSame(int i,int j){ + if(findSet(i) == findSet(j)){ + return true; + } + return false; + } + //returns min max size of i's set + void get(int i){ + cout << "min:" << get_min(i) << " max:" << get_max(i) << " size of set:" < -using namespace std; +using std::cout; +using std::endl; +using std::vector; class DSU{ private: @@ -12,7 +14,7 @@ class DSU{ vector p,depth,setSize; public: //parameter : int n -> maximum number of items - DSU(int n){ + explicit DSU(int n){ p.assign(n,0); //initially all of them their own parents depth.assign(n,0); @@ -43,7 +45,7 @@ class DSU{ //always keeping the min as x //in order to create a shallow tree if(depth[x]>depth[y]){ - swap(x,y); + std::swap(x,y); } //making the shallower tree' root parent of the deeper root p[x] = y; @@ -73,8 +75,7 @@ class DSU{ }; int main(){ - int n; - n = 10; + int n = 10; //n: number of items DSU d(n+1); d.unionSet(2,1); //performs union operation on 1 and 2 @@ -93,4 +94,5 @@ int main(){ d.getParents(2); + return 0; } \ No newline at end of file