一、题目
二、代码
/*
UnionFindSet.h
并查集,非递归方法,含路径压缩,数组从0开始
*/
#include <iostream>
using namespace std;
#define MAXN 30005
class UFS
{
public:
int n;
int p[MAXN+1];//集合根结点
int rank[MAXN+1]; //集合中点的个数
int depth[MAXN+1];
public:
UFS(int size = MAXN);
void clear();
int Find_Set(int x);
//a并入b中,不区分大小
void Union(int x, int y);
void Make_Set(int x);
void Link(int x, int y);
void Graft(int r, int v);
};
UFS::UFS(int size):n(size)
{
//必须从0开始
for(int i = 0; i <= n; i++)
Make_Set(i);
}
void UFS::Make_Set(int x)
{
p[x] = x;
rank[x] = 0;
depth[x] = 0;
}
void UFS::clear()
{
for(int i = 0; i <= n; i++)
Make_Set(i);
}
int UFS::Find_Set(int x)
{
int temp = x,sum = 0,ans;
while(temp != p[temp]) {
sum = sum + depth[temp];
temp = p[temp];
}
ans = temp;
while(x != ans) {
sum -= depth[x];
depth[x] += sum;
temp = p[x];
p[x] = ans;
x = temp;
}
return ans;
}
void UFS::Union(int x, int y)
{
if(x == y)
return ;
Link(x, y);
}
void UFS::Link(int x, int y)
{
p[x] = y;
depth[x] = 1;
rank[y] += rank[x];
}
void UFS::Graft(int r, int v)
{
int x = Find_Set(r);
int y = Find_Set(v);
if(x < y)
Union(x, y);
else
Union(y, x);
}