From 9e7312b6d82ad387b90f6984d0891593171d3e95 Mon Sep 17 00:00:00 2001 From: adityabandal Date: Mon, 26 Oct 2020 11:31:18 +0530 Subject: [PATCH 1/2] Added Union-Find Data Structure --- Data-Structures/Union-Find.cpp | 92 ++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Data-Structures/Union-Find.cpp diff --git a/Data-Structures/Union-Find.cpp b/Data-Structures/Union-Find.cpp new file mode 100644 index 0000000..a456865 --- /dev/null +++ b/Data-Structures/Union-Find.cpp @@ -0,0 +1,92 @@ +#include +using namespace std; + +class UnionFind +{ +private: + int numberOfComponents; + vector parent; + vector size; + +public: + UnionFind(int n) + { + numberOfComponents = n; + parent = vector(n); + size = vector(n); + + for (int i = 0; i < n; i++) + { + parent[i] = i; + size[i] = 1; + } + } + + //returns root node of the component where p belongs + int find(int n) + { + int root = n; + + //find root of this component + while (parent[root] != root) + { + root = parent[root]; + } + + //path-compression i.e. making all nodes in the route to point directly to the root + while (parent[n] != n) + { + int temp = parent[n]; + parent[n] = root; + n = temp; + } + return root; + } + + //unites two components of n1 and n2 + void unite(int n1, int n2) + { + int root1 = find(n1); + int root2 = find(n2); + + if (root1 == root2) //if belong to same component then no need to unite + return; + if (size[root1] < size[root2]) + { + size[root2] += size[root1]; + parent[root1] = root2; + } + else + { + size[root1] += size[root2]; + parent[root2] = root1; + } + //number of components decrease by one + numberOfComponents--; + } + + //returns number of different components + int getNumberOfComponents() + { + return numberOfComponents; + } + + //returns true if n1 and n2 belong to same component and false otherwise + bool isConnected(int n1, int n2) + { + return find(n1) == find(n2); + } +}; + +// int main() +// { +// UnionFind uf(10); +// cout << uf.find(5) << endl; +// cout << uf.getNumberOfComponents() << endl; +// uf.unite(6, 5); +// cout << uf.find(5) << endl; +// cout << uf.getNumberOfComponents() << endl; +// cout << uf.isConnected(1, 2) << endl; + +// return 0; +// } \ No newline at end of file From 69987e35689802259e659b5de1594e142228a5eb Mon Sep 17 00:00:00 2001 From: adityabandal Date: Mon, 26 Oct 2020 11:34:00 +0530 Subject: [PATCH 2/2] Added Union-Find Data Structure --- Data-Structures/Union-Find.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Data-Structures/Union-Find.cpp b/Data-Structures/Union-Find.cpp index a456865..40b16e4 100644 --- a/Data-Structures/Union-Find.cpp +++ b/Data-Structures/Union-Find.cpp @@ -1,3 +1,7 @@ +/* +Implements Unioun Find operations +Complexity: O(logN) amortized is O(1) +*/ #include using namespace std;