View Code
1 #include<stdio.h> 2 int father[100005],members[100005]; 3 int find(int a) 4 { 5 if(father[a]!=a) 6 father[a]=find(father[a]); 7 return father[a]; 8 }//寻找祖先 9 int main() 10 { 11 int i,m,n,b,a,num=1; 12 char ch; 13 while(scanf("%d%d",&n,&m)==2) 14 { 15 if (num!=1) printf("\n"); 16 printf("Case %d:\n",num++); 17 for(i=1;i<=n;i++) 18 { 19 father[i]=i; 20 members[i]=1; 21 }//初始化 22 for(i=0;i<m;i++) 23 { 24 getchar(); 25 scanf("%c",&ch); 26 if(ch=='M') 27 { 28 scanf("%d%d",&a,&b); 29 if(find(a)!=find(b)) 30 { 31 members[find(a)]+=members[find(b)]; 32 father[find(b)]=father[find(a)];//把b接到a的祖先下面 33 } 34 } 35 if(ch=='Q') 36 { 37 scanf("%d",&a); 38 printf("%d\n",members[find(a)]); 39 } 40 } 41 } 42 return 0; 43 }