2 3 3 T 1 2 T 3 2 Q 2 3 4 T 1 2 Q 1 T 1 3 Q 1
Case 1: 2 3 0 Case 2: 2 2 1 3 3 2
题意:
有N的龙珠,编号为1~N,开始时分别分布在编号为1~N的城市。
然后如果是输入T a b,那么进行移动, 把编号a的龙珠所在的城市的所有龙珠移动到编号b龙珠所在的城市。
输入Q a, 那么输出a龙珠所在的城市, a龙珠所在城市有的龙珠的个数, 以及a龙珠移动的次数。
思路:
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#define MAXN 10002
using namespace std;
int N, Q, father[MAXN], rank[MAXN], num[MAXN];
void init(){
for(int i=1; i<=N; ++i){
father[i] = i, rank[i] = 1, num[i]=0;
}
}
int find(int x){
if(x==father[x]) return x;
int t=father[x];
father[x] = find(father[x]);
num[x] += num[t];
return father[x];
}
void Union(int x,int y){
int a=find(x);
int b=find(y);
if(a!=b){
father[a] = b;
rank[b] += rank[a];
num[a] = 1; // 这是球a第一次移动
}
}
int main(){
#ifdef LOCAL
freopen("input.txt","r",stdin);
#endif
int T,a,b,k,cas=1; char cmd[2];
scanf("%d", &T);
while(T--){
printf("Case %d:\n",cas++);
scanf("%d %d", &N,&Q);
init();
for(int i=0; i<Q; ++i){
scanf("%s", cmd);
if(cmd[0]=='T'){
scanf("%d %d", &a, &b);
Union(a, b);
}
else{
scanf("%d", &k);
int x = find(k);
int cnt=0;
printf("%d %d %d\n", x, rank[x],num[k]);
}
}
}
return 0;
}