Skip to content

Instantly share code, notes, and snippets.

@aajjbb
Created June 18, 2012 02:12
Show Gist options
  • Save aajjbb/2946423 to your computer and use it in GitHub Desktop.
Save aajjbb/2946423 to your computer and use it in GitHub Desktop.
Cool UnionFind implementation
#include <iostream>
using namespace std;
struct UnionFind {
int N, *id, *sz;
UnionFind(int _N) {
N = _N;
id = new int[_N];
sz = new int[_N];
for(int i = 0; i < _N; i++) {
id[i] = i;
sz[i] = 1;
}
}
int root(int i) {
while(i != id[i]) {
id[i] = id[id[i]];
i = id[i];
}
return i;
}
bool find(int p, int q) {
return root(p) == root(q);
}
void unite(int p, int q) {
int i = root(p);
int j = root(q);
if(sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
} else {
id[j] = i;
sz[i] += sz[j];
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment