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
6M 1 6C 1M 2 4M 2 6C 3C 4
Sample Outpu1
02
题目意思:有n块方块,p次操作,两种类型,'M a b' 意思是将含有方块a的堆挪到b上:‘C a’意思是查询方块a下面有几个方块。
解题思路:这道题要使用并查集来进行计算。首先为什么会考虑使用并查集呢?因为每一次操作都是把含有a的堆挪到b上,这个时候将会把b包含到这个堆里面,重新组合成一个新的堆,这是什么?状态划分。这道题的难点主要在于虽然在了同一个集合中,但要询问这个集合内的关系,查询a下面几个方块,就可以看成其在集合中的深度。sum[n]数组来统计当前堆n中方块个数。under[n]数组来统计当前n下面的方块个数。在进行计算的时候,路径压缩和合并均更新under的值。未进行路径压缩的时候,方块n所记录的under并非final value, 仅仅只是包含了到root[n]的方块个数。 通过路径压缩的过程,不断的增加当前n的根节点(递归)的under值,求出最终的under值。进行路径合并的时候,更新sum值和under值。当一个堆放在另一个堆上时,被移动的堆的under值一定为0, 此时更新under值为另一个堆的根的sum值,即计算出了此处的部分under值。然后更新合并堆的sum值。1 #include2 #include 3 #define maxs 30010 4 using namespace std; 5 int pre[maxs]; 6 int sum[maxs]; 7 int under[maxs]; 8 void init() 9 {10 int i;11 for(i=0; i