带有权值的并查集 POJ 1988 (Cube Stacking)

Cube Stacking
Time Limit: 2000MS

Memory Limit: 30000K
Total Submissions: 27850

Accepted: 9759
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
这个题目我WA了三次,原因是数据更新的不对,在数据进行更改后不能及时的优先更新,在这里带有权值的数据更新,递归要比循环好的多,能够避免由于后面更改前面的更改呆滞。

//带有权值的并查集,权值附加规则为,
//该点到根节点的距离就是该点到父节点的距离
//与父节点到根节点的距离之和
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#define MAXN 30005
using namespace std;
int up[MAXN];
int down[MAXN];
int father[MAXN];

int mfind(int x){
    if(x!=father[x]){
        int tmp = father[x];
        father[x] = mfind(father[x]);
        down[x] += down[tmp];
    }
    return father[x];
}
void moveto(int x,int y){
    int nx = mfind(x);
    int ny = mfind(y);
    //printf("#%d,%d,%d\n",nx,ny,up[ny]);
    if(nx!=ny){
        father[nx] = ny;
        down[nx]+=up[ny];
        up[ny]+=up[nx];
    }
}
int main()
{
    int n;
    while(~scanf("%d",&n)){
        memset(down,0,sizeof(down));
        for(int i=1;i<MAXN;i++){
            father[i] = i;
            up[i] = 1;
        }
        char operation;
        getchar();
        for(int i=0;i<n;i++){
            scanf("%c",&operation);
            if(operation=='M'){
                int beg,ed;
                scanf("%d%d",&beg,&ed);
                moveto(beg,ed);
            }
            else{
                int seek;
                scanf("%d",&seek);
                mfind(seek);
                printf("%d\n",down[seek]);
            }
            getchar();
        }
    }
    return 0;

}
老师讲过让我们使用循环进行并查集带权值的处理,可是我就是写不出来,智商不在线吧!如果有哪位小伙伴有什么好点的代码的话,请评论给我,非常感谢!!!!

猜你喜欢

转载自blog.csdn.net/weixin_40488730/article/details/81569504