POJ1988 Cube Stacking【带权并查集 统计】

Cube Stacking

Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 28711   Accepted: 10081
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

USACO 2004 U S Open

问题链接:POJ1988 Cube Stacking

问题描述:有n个相同的立方体(从1开始编号),开始有n堆(每堆一个),有P次操作,每次有两种选择,操作一M X Y,将包含立方体X的一堆移动包含立方体Y的一堆的上面,操作二C X,查询立方体X下面的立方体的个数。对于每个查询操作,输出相应的答案。

解题思路:带权并查集,让每堆中各个立方体都以最顶上的立方体为祖先结点,设结点 i 的祖先结点为 j ,cnt[i] 表示结点 i 到 j之间的立方体数,sum[j]表示以结点 j 为祖先结点的立方体数,则C i 的结果为 sum[j] - cnt[i]

AC的C++代码:

#include

using namespace std;

const int N=30010;
int pre[N],cnt[N],sum[N];//pre存储结点i的父节点,cnt存储结点i到父结点之间的立方体数,sum存储以结点i为祖先结点的立方体数

void init()
{
	for(int i=0;i

 

你可能感兴趣的:(数据结构)