HDU-3635-Dragon Balls
http://acm.hdu.edu.cn/showproblem.php?pid=3635
并查集,路径压缩来更新转移的次数
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
#define N 10005
struct cam
{
int f;
int num;
int cnt;
}list[N];
int n;
int find(int x) //查询父亲结点,并且加上转移的次数
{
int temp;
if(x!=list[x].f)
{
temp=list[x].f;
list[x].f=find(temp);
list[x].cnt+=list[temp].cnt;
}
return list[x].f;
}
void merege(int x,int y) //将x转至y
{
int xx,yy;
xx=find(x);
yy=find(y);
if(xx==yy)
return;
list[xx].f=yy;
list[yy].num+=list[xx].num;
list[xx].cnt++; //根节点加1
}
int main()
{
int k,t,q,i,m;
int a,b;
char ch;
scanf("%d",&t);
for(k=1;k<=t;k++)
{
scanf("%d%d",&n,&q);
for(i=1;i<=n;i++)
{
list[i].f=i;
list[i].num=1;
list[i].cnt=0;
}
printf("Case %d:\n",k);
while(q--)
{
getchar();
scanf("%c",&ch);
if(ch=='T')
{
scanf("%d %d",&a,&b);
merege(a,b);
}
else
{
scanf("%d",&a);
m=find(a);
printf("%d %d %d\n",list[m].f,list[m].num,list[a].cnt);
}
}
}
return 0;
}