poj1988_Cube Stacking

Posted 多一份不为什么的坚持

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj1988_Cube Stacking相关的知识,希望对你有一定的参考价值。

Cube Stacking
Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 24130   Accepted: 8468
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

Source

唉,一个并查集的题,改了好久。。。终于a了。
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 int up[300005];//该数上面的数
 8 int n[300005];//该集合总数
 9 int a[300005];//保存他的父节点
10 
11 int father(int t){
12     if(t==a[t]){
13         return t;
14     }
15     int fa=a[t];
16     a[t]=father(a[t]);
17     up[t]+=up[fa];
18 
19     return a[t];
20 }
21 
22 int main()
23 {
24     int p;
25     //char c;
26     int t1,t2;
27     int t3;
28 while(scanf("%d",&p)!=EOF){
29     for(int i=0;i<=p;i++){
30         a[i]=i;
31         up[i]=0;
32         n[i]=1;
33     }
34     char s[10];
35     for(int i=0;i<p;i++){
36         scanf("%s",s);
37         if(s[0]==M){
38             scanf("%d%d",&t1,&t2);
39             int fa=father(t1);
40             int fb=father(t2);
41             if(fa!=fb){
42                 a[fb]=fa;
43                 up[fb]+=n[fa];
44                 n[fa]+=n[fb];
45             }
46         }else{
47             scanf("%d",&t3);
48             int ans=father(t3);
49             printf("%d\n",n[ans]-up[t3]-1);
50         }
51     }
52 }
53     return 0;
54 }

 

以上是关于poj1988_Cube Stacking的主要内容,如果未能解决你的问题,请参考以下文章

POJ 1988 Cube Stacking (带权并查集)

POJ 1988 Cube Stacking

POJ 1988 Cube Stacking

POJ 1988 Cube Stacking

加权并查集——(POJ1988)Cube Stacking

POJ 1988 Cube Stacking (带权并查集)