Cube Stacking

发布于:2022-11-28 ⋅ 阅读:(379) ⋅ 点赞:(0)

1988:Cube Stacking

总时间限制: 

2000ms

单个测试点时间限制: 

1000ms

内存限制: 

65536kB

描述

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.

输入

* 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.

输出

Print the output from each of the count operations in the same order as the input file.

样例输入

6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4

样例输出

1
0
2

来源

USACO 2004 U S Open

思路:
  题意说是有n块砖,编号从1到n,有两种操作,操作一(‘M’)是把含有x编号的那一堆砖放到含有编号y的那一堆砖的上面,操作二(‘C’)是查询编号为x的砖的下面有多少块砖。传统并查集+维护size和deep两个数组,find函数在路径压缩的过程中需要把深度也依次加上,到代表这里的时候就是这个集合的最大深度,合并过程中要先将被合并的个数加到合并别人的集合的深度上去,然后在合并个数,最后将被合并的集合清零。

#include<iostream>
#include<algorithm>
#include<stdio.h>
const int N =1e5+5;
using namespace std;
int deep[N];
int size[N];
int p[N];
int find(int x)
{
    if(p[x]!=x) 
    {
        int t=p[x];
        p[x]=find(p[x]);
        deep[x]+=deep[t];
    }
    return p[x];
}
void Union(int x,int y)
{
    int xx=find(x);
    int yy=find(y);
    if(xx!=yy)
    {
        p[xx]=yy;
        deep[xx]+=size[yy];
        size[yy]+=size[xx];
        size[xx]=0;
    }
}
int main()
{
	int n; 
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        p[i]=i;
        size[i]=1;
    }
    for(int i=1;i<=n;i++)
    {
        char op[5];
        scanf("%s",op);
        if(op[0]=='M')
        {
            int a,b;
            scanf("%d %d",&a,&b);
            Union(a,b);
        }
        else if(op[0]=='C')
        {
            int a;
            scanf("%d",&a);
            find(a);
            printf("%d\n",deep[a]);
        }
    }
    return 0;
}

该题链接:

OpenJudge - 1988:Cube Stackinghttp://bailian.openjudge.cn/practice/1988 

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到