Cube Stacking
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
题目大意:
有一些堆栈(最多30000个),给你m个操作,每个操作有两种指令:“M x y”--> 移动,将含有元素x的堆栈移动到含有元素y的堆栈最上方、“C x”-->查询,查询元素x下方元素个数。
解题思路:
显而易见,判断堆栈元素关系,并查集。f数组存储根节点,另开两个数组top和ans,top存储该元素上方有多少元素,ans数组存储该元素所在堆栈元素总数。那么,x元素下方元素 = x元素所在堆栈总元素个数 - x元素上方元素 - 1(本身)。具体执行看代码注释。
AC代码:
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
#define MAXN 30010
int f[MAXN], top[MAXN], ans[MAXN];
//f 数组表示该元素所在堆栈的最上方元素(根)
//top 数组表示该元素上方有多少元素
//ans 数组表示该堆栈最上方元素所在堆栈的元素总数
int getf( int v )
{
if( v != f[v] )//若该元素不是堆栈最上方元素(根),需更新数组
{
int t = f[v];//该元素当前的根
f[v] = getf(f[v]);//更新该元素所在堆栈的最上方元素(根)
top[v] += top[t];//该元素上方元素个数为本身个数加上根元素上方个数
}
return f[v];//返回最上方(根)元素
}
void lian( int t1, int t2 )
{
int v1 = getf(t1);//需要移动的那个堆栈的最上方(根)元素
int v2 = getf(t2);//加入该堆栈之前,该堆栈的最上方(根)元素
if( v1 != v2 )//两个不是同一堆栈(其实肯定不是同一堆栈)
{
f[v2] = v1;//新堆栈的最上方(根)元素
top[v2] = ans[v1];//之前堆栈根元素上方就有了加入的堆栈的所有元素
ans[v1] += ans[v2];//新堆栈的元素总数就是两个堆栈元素数之和
}
}
int main()
{
int n;
while( ~scanf("%d",&n) )
{
for( int i = 1; i < MAXN; i++ )
{
f[i] = i;//初始化所有根节点都是自己
ans[i] = 1;//初始化所有元素所在堆栈的元素个数是1(自己一个)
top[i] = 0;//初始化所有元素上方无元素
}
char cz;
int t1, t2;
for( int i = 0; i < n; i++ )
{
cin>>cz;
if( cz == 'M' )
{
scanf("%d%d",&t1,&t2);
lian(t1,t2);
}
else
{
scanf("%d",&t1);
printf("%d\n",ans[getf(t1)]-top[t1]-1);
//t1下方元素个数就是t1所在堆栈的总元素个数-t1上方元素个数-本身
}
}
}
return 0;
}