标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4357 Accepted Submission(s): 1661
1 #include <cstdio> 2 #include <iostream> 3 using namespace std; 4 int father[10001], ran[10001], num[10001] ; //位置, 节点数, 转换次数; 5 int i, n; 6 void init() 7 { 8 for(i=1; i<=n; i++) 9 { 10 father[i]=i; ran[i]=1; num[i]=0; 11 } 12 } 13 int find(int a) 14 { 15 if(a != father[a]) 16 { 17 int k = father[a]; 18 father[a] = find(father[a]); 19 num[a] += num[k]; //递归计算转化次数;(每个节点只移动一次, 然后跟随父节点一起移动) 20 } 21 return father[a]; 22 } 23 void mercy(int a, int b) 24 { 25 int q = find(a); 26 int p = find(b); 27 if(q != p) 28 { 29 father[q] = p; 30 ran[p] += ran[q]; 31 num[q] = 1; 32 } 33 } 34 int main() 35 { 36 int t, m, a, b, c, temp=1; char str[2]; 37 scanf("%d", &t); 38 while(t--) 39 { 40 printf("Case %d:\n",temp++); 41 scanf("%d %d", &n, &m); 42 init(); 43 while(m--) 44 { 45 scanf("%s", str); 46 if(str[0] == ‘T‘) 47 { 48 scanf("%d %d", &a, &b); 49 mercy(a, b); 50 } 51 else 52 { 53 scanf("%d", &c); 54 int k = find(c); 55 printf("%d %d %d\n", k, ran[k], num[c]); 56 } 57 } 58 } 59 return 0; 60 }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4694717.html