带权并查集 poj Cube Stacking

Cube Stacking

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

题目链接:http://poj.org/problem?id=1988

题意:有n个方块,进行m次操作。有两种操作类型,M a b 将含有a的堆放在包含b的堆上,还有一种是 C a统计a下面有多少个方块。

带全并查集裸模板,用两个数组表示该点到根节点一共有多少个,和表示该点的下面有多少个。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn = 1e6+5;

int father[maxn];
int sum[maxn];
int dis[maxn];

int find(int x)
{
    if(x != father[x])
    {
        int f = father[x];
        father[x] = find(father[x]);
        sum[x] += sum[f];
    }
    return father[x];
}

int main()
{
    int m;
    cin >> m;
    for(int i = 1; i <= m; i++)
    {
        father[i] = i;
        sum[i] = 0;
        dis[i] = 1;
    }
    while(m --)
    {
        char op;
        int x, y;
        cin >> op;
        if(op == 'M')
        {
            cin >> x >> y;
            int fx = find(x);
            int fy = find(y);
            if(fx != fy)
            {
                father[fx] = fy;
                sum[fx] += dis[fy];
                dis[fy] += dis[fx];
            }    
        }
        else
        {
            cin >> x;
            int fx = find(x);
            cout << sum[x] << endl;    
        } 
    }
    return 0;    
}

猜你喜欢

转载自blog.csdn.net/qq_38295645/article/details/81741961