标签:
1 #include<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 using namespace std; 5 int ball[10010],ti[10010],q[10010],N; 6 int find(int x){int temp=ball[x]; 7 if(x==ball[x])return x; 8 ball[x]=find(ball[x]);//此处递归找到父节点; 9 q[x]+=q[temp];//找到父节点后逐步执行下面这句话,temp的值随这递归被保存着; 10 return ball[x];//压缩路径。理解递归就好; 11 } 12 void merge(int x,int y){ 13 int f1,f2; 14 f1=find(x);f2=find(y); 15 if(f1!=f2){ 16 ball[f1]=f2;ti[f2]+=ti[f1]; 17 q[f1]++; 18 } 19 } 20 int main(){char m[5]; 21 int T,A,B,Q,flot=0,k=0; 22 scanf("%d",&T); 23 while(T--){flot++;k=0; 24 scanf("%d%d",&N,&Q); 25 for(int i=1;i<=N;++i)ti[i]=1,ball[i]=i,q[i]=0; 26 printf("Case %d:\n",flot); 27 while(Q--){ 28 scanf("%s",m); 29 if(strcmp(m,"T")==0){ 30 scanf("%d%d",&A,&B); 31 merge(A,B); 32 } 33 else{ 34 scanf("%d",&A); 35 k=find(A);find(A);find(A);find(A);find(A);find(A);find(A);//find(A)放函数里面就出错了; 36 printf("%d %d %d\n",k,ti[k],q[A]); 37 } 38 } 39 } 40 return 0; 41 }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/4700701.html