POJ 1988 Cube Stacking

题目分析

典型的带权并查集,这道题有2个操作,一个是将带a的那一堆石头移到带b的那一堆石头上面,另一个是询问a号石头下面有多少石头。这里我定义了3个数组,fa用于查父节点,he查编号为i的石头下面有多少石头,sum表示以a为根节点的石头堆中有多少石头。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 30005;

int sum[maxn],he[maxn],fa[maxn];  //sum表示这堆石头有多少个,he表示

void init(){
    for(int i = 0; i < maxn; i++){
        sum[i] = 1;
        he[i] = 0;
        fa[i] = i;
    }
}

int Find(int x){
    if(x == fa[x]) return fa[x];
    int temp = Find(fa[x]);
    he[x] += he[fa[x]];
    fa[x] = temp;
    return fa[x];
}

int main()
{
    int P;
    scanf("%d", &P);
    char op;
    int x,y;
    init();
    while(P--){
        cin >> op;
        if(op == 'M') {
            scanf("%d%d", &x, &y);
            int xx = Find(x);
            int yy = Find(y);
            he[xx] = sum[yy];
            sum[yy] += sum[xx];
            fa[xx] = yy;
        }else{
            scanf("%d", &x);
            Find(x);
            printf("%d\n", he[x]);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值