您的位置:首页 > 其它

POJ 1988 Cube Stacking

2015-08-15 22:46 369 查看
POJ 1988 Cube Stacking

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

题意给你 1-n 编号的立方体,然后移动含有指定编号的立方体

栈移到另一个栈上边,问指定的编号立方体下面有多少个立方体。

*

应用 并查集的思路,移动一个栈时,相当于union_set操作,只要另开一个

数组记录立方体的位置,当合并时,只要改变根节点的位置记录就可以了,

这个地方并查集用的比较巧妙。其余的就是基本的并查集操作了。

*/

[code]#include<iostream>
#include <string.h>
#include <cstdio>
#define N 30003
using namespace std;
int u
, top
, cnt
, n;

void init()
{
    for (int i = 0; i < N; i++)
    {
        u[i] = i;
        top[i] = 0;
        cnt[i] = 1;
    }
}

int find(int x)
{
    if (x != u[x])
    {
        int t = find(u[x]);
        top[x] += top[u[x]];
        return u[x] = t;
    }
    return x;
}

void un(int x, int y)
{
    x = find(x);
    y = find(y);
//  if (x == y)
    {
//      return ;
    }
    u[y] = x;
    top[y] = cnt[x];
    cnt[x] += cnt[y];
}

int main()
{
#ifndef  ONLINE_JUDGE
    freopen("1.txt", "r", stdin);
#endif
    int a, b;
    char ch;
    while(~scanf("%d", &n))
    {
        init();
        while(n--)
        {
            cin >> ch;
            if (ch == 'M')
            {
                cin >> a >> b;
                un(a, b);
            }
            else
            {
                cin >> a;
                b = find(a);
                cout << cnt[b] -top[a] - 1 << endl;
            }
        }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: