From 5a8f14a316af42504b77c35498aaa3b73f348c8c Mon Sep 17 00:00:00 2001 From: hamzahasann <64196922+hamzahasann@users.noreply.github.com> Date: Sun, 9 Oct 2022 01:56:10 +0500 Subject: [PATCH] Create disjoint_union_set.cpp Classic disjoint set union data structure in c++. --- .../DisjointSetUnion/disjoint_set_union.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 algorithms/CPlusPlus/DisjointSetUnion/disjoint_set_union.cpp diff --git a/algorithms/CPlusPlus/DisjointSetUnion/disjoint_set_union.cpp b/algorithms/CPlusPlus/DisjointSetUnion/disjoint_set_union.cpp new file mode 100644 index 00000000..70bae031 --- /dev/null +++ b/algorithms/CPlusPlus/DisjointSetUnion/disjoint_set_union.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +/* +Disjoint set union data structure supporting find and union operations. +Time Complexity: O(a(N)) where a(N) is the Inverse Ackerman function. +*/ +const int N=1e3; +vectorP(N),S(N); + +// create new node +void create(int u){ + P[u]=u;S[u]=1; +} +// find parent of node +int find(int u){ + if(u==P[u])return u; + return P[u]=find(P[u]); +} +// merge 2 nodes +void merge(int u,int v){ + u=find(u); + v=find(v); + if(u!=v){ + if(S[u]