裸并查集操作.
#include <stdio.h>
int id[100001], size[100001], n, m;
void readInt(int * x){
char ch;
*x = 0;
ch = getchar();
while(!(ch >= '0' && ch <= '9'))ch = getchar();
while(ch >= '0' && ch <= '9'){
*x = *x * 10 + ch -'0';
ch = getchar();
}
}
void init(){
int i;
for(i = 1; i <= n; ++i){
id[i] = i;
size[i] = 1;
}
}
int find(int p){
while(p != id[p]){
id[p] = id[id[p]];
p = id[p];
}
return p;
}
void uni(int p, int q){
int pp = find(p), pq = find(q);
if(pp == pq)return;
if(size[pp] > size[pq]){
id[pq] = pp;
size[pp] += size[pq];
}else{
id[pp] = pq;
size[pq] += size[pp];
}
}
int main(){
int cas = 1;
while(scanf("%d%d\n", &n, &m) == 2){
if(cas > 1)printf("\n");
printf("Case %d:\n",cas++);
init();
while(m--){
char ch = getchar();
if(ch == 'M'){
int x, y;
readInt(&x), readInt(&y);
uni(x, y);
}else{
int x;
readInt(&x);
printf("%d\n", size[find(x)]);
}
}
}
return 0;
}