Cube Stacking

来源:互联网 发布:https的默认端口 编辑:程序博客网 时间:2024/06/07 01:13

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
m操作代表把含有x的一摞挪到含有y的一摞,c操作是问x下面有多少个方块。一开始我开了两个并查集,一个从上到下,一个从下到上,可想而知,t了。这才知道有种东西叫路径压缩,设一个变量,代表他到祖先的距离,就是在他下面的方块个数了。此外,还要设一个该摞方块个数的变量,这样合并的时候,被摞的一方只需要加上这个个数就可以更新在他下面方块的个数了,此外,该摞方块个数也多了新来一方的个数。

#include<cstdio>#include<cstring>#include<iostream>#include<queue>#include<vector>#include<algorithm>#include<string>#include<cmath>#include<set>#include<map>#include<vector>using namespace std;typedef long long ll;const int inf = 0x3f3f3f3f;const int maxn = 1005;int p[30005],num[30005],r[30005];void init(){    for(int i = 1;i <= 30000;i++)    {        p[i] = i;r[i] = 0;num[i] = 1;    }}int find(int x){    if(x != p[x])    {        int fx = find(p[x]);        r[x] += r[p[x]];        p[x] = fx;    }    return p[x];}void union_set(int x,int y){    int fx = find(x);    int fy = find(y);    p[fx] = fy;    r[fx] += num[fy];    num[fy] += num[fx];}int main(){    #ifdef LOCAL    freopen("C:\\Users\\巍巍\\Desktop\\in.txt","r",stdin);    //freopen("C:\\Users\\巍巍\\Desktop\\out.txt","w",stdout);    #endif // LOCAL    int p;    scanf("%d",&p);getchar();    init();    while(p--)    {        int x,y;        char c;        scanf("%c",&c);        if(c == 'C')        {            scanf("%d",&x);getchar();            find(x);            printf("%d\n",r[x]);        }        else if(c == 'M')        {            scanf("%d%d",&x,&y);getchar();            union_set(x,y);        }    }    return 0;}
0 0
原创粉丝点击