C++版本:
按秩合并的并查集
int init(int n) { //初始化
for (int i = 0; i < n; i++) {
fa[i] = i;
rank[i] = 0;
}
}
int find(int x) { //查询
if (fa[x] == x) {
return x;
}
else {
return find(fa[x]);
}
}
void unite(int x, int y) { //合并
x = find(x);
y = find(y);
if (x == y)return;
if (rank[x] < rank[y]) {
fa[x] = y;
}
else {
fa[y] = x;
if (rank[x] == rank[y])rank[x]++;
}
}
bool same(int x, int y) {
return find(x) == find(y);
}
带权并查集
int ABs(int x) {
return x >= 0 ? x : (-1)*x;
}
void INit(int n) {
for (int i = 0; i <= n; i++)fa[i] = i, num[i] = 1;
}
int FInd(int x) {
if (fa[x] != x) {
int k = fa[x];
fa[x] = FInd(fa[x]);
dist[x] += dist[k];
num[x] = num[fa[x]];
}
return fa[x];
}
void UNite(int x, int y) {
x = FInd(x), y = FInd(y);
if (x != y) {
fa[x] = y;
dist[x] = dist[y] + num[y];
num[y] += num[x];
num[x] = num[y];
}
}
int QUery(int x, int y) {
int xd = FInd(x), yd = FInd(y);
if (xd != yd) {
return -1;
}
else return ABs(dist[x] - dist[y]) - 1;
}