poj 1988 (并查集)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
using namespace std;
#define MAXN 30010
int father[MAXN],rank[MAXN];
int num[MAXN]; //根节点x记录集合的数量
void make_set(int x)
{
father[x]=x;
num[x]=1;//初始化每个根节点x的数量为1
}
int find_set(int x)
{
if(x==father[x]) return x;
else
{
int t=father[x];
father[x]=find_set(father[x]);
rank[x]=rank[x]+rank[t]; //压缩路径
return father[x];
}
}
void union_set(int x,int y)
{
int rx=find_set(x);
int ry=find_set(y);
father[rx]=ry;
rank[rx]=num[ry];
num[ry]+=num[rx];
}
int main()
{
int i,n,x,y;
char c[10];
scanf("%d",&n);
for(i=1;i<=30000;i++)
make_set(i);
while(n--)
{
scanf("%s",c);
if(c[0]=='M')
{
scanf("%d%d",&x,&y);
int rx=find_set(x);
int ry=find_set(y);
if(rx!=ry)
union_set(x,y);
}
else
{
scanf("%d",&x);
find_set(x);
printf("%d\n",rank[x]);
}
}
return 0;
}
posted on 2011-06-10 16:35 thinking001 阅读(87) 评论(0) 收藏 举报
浙公网安备 33010602011771号