POJ - 1988 Cube Stacking 【带权并查集】

Cube Stacking
Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 27036   Accepted: 9482
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


思路:

可以用sum[]存堆顶元素所在堆有多少元素,再用一个len【】记录节点到堆顶的距离。计算时用sum[i]-len[i]-1。计算len时,find函数返回时更新len,merge时需要更新根节点的len。


代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAXN 30005
int n,m,pre[MAXN],sum[MAXN],len[MAXN];
int find(int u)
{
    if(pre[u]==u) return u;
    int r=find(pre[u]);
    len[u]+=len[pre[u]];
    return pre[u]=r;
}
int merge(int u,int v)
{
    int f1=find(u);
    int f2=find(v);
    if(f1!=f2)
    {
        pre[f2]=f1;
        len[f2]+=sum[f1];
        sum[f1]+=sum[f2];
        return 1;
    }
    return 0;
}
int main()
{
    n=30000;
    while(~scanf("%d",&m))
    {
        for(int i=1;i<=n;i++)
            pre[i]=i,sum[i]=1;
        memset(len,0,sizeof len);
        for(int i=0;i<m;i++)
        {
            char op[2];
            int u,v;
            scanf("%s",op);
            if(op[0]=='M')
            {
                scanf("%d%d",&u,&v);
                merge(u,v);
            }
            else
            {
                scanf("%d",&u);
                printf("%d\n",sum[find(u)]-len[u]-1);
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u013852115/article/details/80089781