Shirlies
宁静专注认真的程序媛~

题意:起初球i是被放在i号城市的,在年代更迭,世事变迁的情况下,球被转移了,而且转移的时候,连带该城市的所有球都被移动了:T A B(A球所在的城市的所有球都被移动到了B球所在的城市),Q A(问:A球在那城市?A球所在城市有多少个球呢?A球被转移了多少次呢?)。

这一题还是蛮有意思的,虽然第一次写的时候超时了,因为我没有利用好查找函数的递归性,在合并的时候用一个循环将本来可以在查找时就合并好的,又另外处理的。

View Code
 1 #include <cstdio>
2 #include <string>
3 #define MAX 10010
4
5 int rank[MAX];//记录移动的次数
6 int f[MAX];
7 int ad[MAX];//记录某城市的球的数量
8 int n,m;
9
10 int find(int x)
11 {
12 if(x==f[x])
13 return x;
14 int t=find(f[x]);
15 rank[x] += rank[f[x]] ;
16 f[x] = t;
17 return t;
18 }
19
20 void join(int x,int y)
21 {
22 if(x == y)
23 return ;
24 //int t = f[x];
25 f[x] = y;
26 rank[x] = 1;
27 ad[y] += ad[x] ;
28 }
29
30 int main()
31 {
32 int cas;
33 int num = 1;
34 scanf("%d",&cas);
35 while(cas --)
36 {
37 scanf("%d%d",&n,&m);
38 getchar();
39 memset(rank,0,sizeof(rank));
40 //memset(ad , 0 ,sizeof(ad));
41 int i;
42 for(i = 1;i <= n;i ++)
43 {
44 f[i] = i;
45 ad[i] = 1;
46 }
47
48 char ch;
49 int a,b,q;
50 int fa,fb;
51
52 printf("Case %d:\n",num ++);
53 for( i = 0; i < m ; i ++)
54 {
55 scanf("%c",&ch);
56
57 //printf("*%c\n",ch);
58 if(ch == 'T')
59 {
60 scanf("%d%d",&a,&b);
61 fa = find(a);
62 fb = find(b);
63 join (fa,fb);
64 getchar();
65 }
66 else
67 {
68 scanf("%d",&q);
69 int fq = find(q);
70 printf("%d %d %d\n",fq,ad[fq],rank[q]);
71 getchar() ;
72 }
73
74 }
75 }
76
77 return 0;
78 }
79
80
81

 

 

posted on 2012-03-06 16:11  Shirlies  阅读(1376)  评论(1编辑  收藏  举报