Created
June 18, 2012 02:12
-
-
Save aajjbb/2946423 to your computer and use it in GitHub Desktop.
Cool UnionFind implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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