poj 1988 Cube Stacking

Cube Stacking
Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 23540   Accepted: 8247
Case Time Limit: 1000MS

Description

Farmer John and Betsy are playing a game with N (1 <= N <= 30,000)identical cubes labeled 1 through N. They start with N stacks, each containing a single cube. Farmer John asks Betsy to perform P (1<= P <= 100,000) operation.  There are two types of operations: moves and counts.   * In a move operation, Farmer John asks Bessie to move the stack containing cube X on top of the stack containing cube Y.   * In a count operation, Farmer John asks Bessie to count the  number of cubes on the stack with cube X that are under the cube X and report that value.
Write a program that can verify the results of the game.

Input

* Line 1: A single integer, P
* Lines 2..P+1: Each of these lines describes a legal operation. Line 2 describes the first operation, etc.  Each line begins with a 'M' for a move operation or a 'C' for a count operation.  For move operations, the line also contains two integers: X and Y.For count operations, the line also contains a single integer: X.
Note that the value for N does not appear in the input file. No move operation will request a move a stack onto itself.

Output

Print the output from each of the count operations in the same order as the input file.

Sample Input

6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4

Sample Output

1
0
2


 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 const int MAX = 30005;
 6 int parent[MAX];
 7 int sum[MAX];//若parent[i]=i,sum[i]表示砖块i所在堆的砖块数
 8 int under[MAX];//under[i]表示砖块i下面有多少砖块
 9 
10 void init(){
11     for(int i = 0; i < MAX; i++){
12         parent[i] = i;
13         sum[i] = 1;
14         under[i] = 0;
15     }
16 }
17 
18 int GetParent(int a){//获取a的根,并把a的父节点改为根
19     if(parent[a] == a)
20         return a;
21     int p = GetParent(parent[a]);
22     under[a] += under[parent[a]];
23     parent[a] = p;
24     return parent[a];
25 }
26 
27 void merge(int a, int b){
28     //把b所在的堆,叠放到a所在的堆。
29     int pa = GetParent(a);
30     int pb = GetParent(b);
31     if(pa == pb)
32         return ;
33     parent[pb] = pa;
34     under[pb] = sum[pa];//under[pb]赋值前一定是0,因为parent[pb] = pb,pb一定是原b所在堆最底下的
35     sum[pa] += sum[pb];
36 }
37 
38 int main(){
39     int p;
40     init();
41     scanf("%d", &p);
42     for(int i = 0; i < p; i++){
43         char s[20];
44         int a, b;
45         scanf("%s", s);
46         if(s[0] == 'M'){
47             scanf("%d%d", &a, &b);
48             merge(b, a);
49         }
50         else {
51             scanf("%d", &a);
52             GetParent(a);
53             printf("%d
", under[a]);
54         }
55     }        
56     return 0;
57 }
原文地址:https://www.cnblogs.com/qinduanyinghua/p/5703987.html