Description
Farmer John and Betsy is 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 is 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 is under the C Ube 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 the INTEGERS:X and y.for count operations, the line also contains a single in Teger:x.
Note that the value of N does not appear in the input file. No move operation would 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
Sample Output
1 0 2
and check Set
?YesN (n<=30,000)Heap blocks, starting each heap is a
Box. Block number1–n.There are two kinds of actions:
?M x y: Indicates that the blockXWhere the heap is, pick it up and fold it
ToYOn the same heap.
? C x: Ask the number of squares below the square x.
? The operation has a maximum of P (p<=100,000) times. For each C
and output results.
Solution:
Apart fromParentArray, and also to open
SumArray: Records how many squares are in each heap.
IfParent[a] = A,Thea block number.
under[i] i How many
1#include <iostream>
2#include <cstring>
3#include <cmath>
4usingnamespaceStd
5
6intfa[110000],sum[110000],under[110000];
7
8intGetfather (intA
9{
Tenif(fa[a]==a)
OnereturnA
AintT=getfather (Fa[a]);
-Under[a]+=under[fa[a]];
-fa[a]=t;
thereturnT
-}
-
-voidMergeintAintb
+{
-intTa=getfather (a);
+intTb=getfather (b);
Aif(TA==TB)
at return;
-UNDER[TA]=SUM[TB];
-FA[TA]=TB;
-SUM[TB]+=SUM[TA];
-}
-intMain ()
in{
-intN,a,b;
toCharCh
+cin>>n;
- for(intI=1; i<=n;i++)
the{
*under[i]=0;
$sum[i]=1;
Panax NotoginsengFa[i]=i;
-}
the while(n--)
+{
Acin>>ch;
theif(ch=='M')
+{
-cin>>a>>b;
$Merge (A, b);
$}
-Else
-{
thecin>>a;
-Getfather (a);
Wuyicout <<under[a]<<endl;
the}
-}
Wureturn0;
-}View Code
POJ 1988 Cube Stacking