Create disjoint_union_set.cpp

Classic disjoint set union data structure in c++.
pull/997/head
hamzahasann 2022-10-09 01:56:10 +05:00 committed by GitHub
parent 04d42af7c0
commit 5a8f14a316
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,33 @@
#include<bits/stdc++.h>
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;
vector<int>P(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]<S[v]){
P[u]=v;
S[v]+=S[u];
}else{
P[v]=u;
S[u]+=S[v];
}
}
}