You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A C/C++ implementation of union by rank and find with path compression. The operations are fast and the implementation uses one array only. Applications include connectivity tests and finding minimum spanning trees (to name a few).
API
init(); // Initialize module
int root(int x); // Returns the representative of the disjoint set containing x
void join(int x, int y); // Unify the sets containing x and y
Implementation
#include<cstdio>
#include<cassert>
#include<vector>
#include<iostream>usingnamespacestd;constint N = 1000010;
int n;
int uf[N];
voidinit( void ) {
for(int i = 0; i < N; i++)
uf[i] = -1;
}
/* Find root of set containing x */introot( int x ) {
int r = x;
/* Find root */while(uf[r] >= 0)
r = uf[r];
/* Compress path to root */while(uf[x] >= 0) {
int tmp = uf[x];
uf[x] = r;
x = tmp;
}
return r;
}
/* Union of sets containing x and y */voidjoin( int x, int y ) {
x = root(x);
y = root(y);
if(x != y) {
if(uf[x] < uf[y]) {
uf[x] += uf[y];
uf[y] = x;
}
else {
uf[y] += uf[x];
uf[x] = y;
}
}
}
/* Example */intmain( void ) {
init();
assert(root(1) != root(2));
join(1, 2);
assert(root(1) == root(2));
join(3, 4);
join(2, 3);
assert(root(1) == root(4));
return0;
}
The text was updated successfully, but these errors were encountered:
union-find
A C/C++ implementation of union by rank and find with path compression. The operations are fast and the implementation uses one array only. Applications include connectivity tests and finding minimum spanning trees (to name a few).
API
init(); // Initialize module
int root(int x); // Returns the representative of the disjoint set containing x
void join(int x, int y); // Unify the sets containing x and y
Implementation
The text was updated successfully, but these errors were encountered: