题目链接:http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=5§ionid=1&problemid=10
题意是:有1-n号龙珠分别对应放在1-n号城市,输入T A B时把A号城市的所有龙珠移到B号城市,输入Q A时,输出A号龙珠所在的城市号码,该城市龙珠的数目,A号龙珠一共被移动了多少次。
题目类型:并查集
#include<iostream>
#include<string>
#define max 10005
using namespace std;
int father[max],sum[max],num[max];
void init(int n){
for(int i = 0;i <= n;i ++){
father[i] = i;
sum[i] = 0;
num[i] = 1;
}
}
int find(int x){
int temp;
if(x == father[x])
return x;
else{
temp = father[x];
father[x] = find(father[x]);
sum[x] += sum[temp];
}
return father[x];
}
void Union(int a,int b){
int x = find(a);
int y = find(b);
if(x == y) return ;
else{
father[x] = y;
sum[x] ++;
num[y] += num[x];
num[x] = 0;
}
}
int main(){
const string t = "T";
string in;
int cas,n,m,x,y,q;
int count = 1;
cin>>cas;
while(cas --){
scanf("%d%d",&n,&m);
init(n);
printf("Case %d:\n",count++);
for(int i = 0;i != m;i ++){
cin>>in;
if(in == t){
scanf("%d%d",&x,&y);
Union(x,y);
}
else{
scanf("%d",&q);
int loc = find(q);
printf("%d %d %d\n",loc,num[loc],sum[q]);
}
}
}
return 0;
}
首先初始化,刚开始每个龙珠的集合就是该龙珠的号码,每个龙珠共被移动次数为0,每个集合含有1个龙珠。
然后是寻找父集合,找的过程中将经过的集合所记录的移动次数全部加起来得到当前集合的移动次数。
并集:若传入的参数a,b不同父集合,把a的父集合并入b的父集合中,就实现了a移到b的要求。