poj(1988)

题目:http://poj.org/problem?id=1988

/*
 带权并查集的题目。
 father[x] 为x的父亲节点(x所在stack顶端的cube)
 weight[x] 为x所在stack包含的cube数量
 up[x] 为在x上方的cube的数量
 则x之下的cube数应为weight[find(x)]-up[x]-1
 即用x的父亲节点所在stack的cube数减去x上面的cube数,再减去x自身
 */
#include<iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn = 30005;
int father[maxn];
int up[maxn];
int weight[maxn];
void make_set(int n){
    for(int i =1;i <= n;i++){
        father[i] = i;
        up[i] = 0;
        weight[i] = 1;
    }
}
int find_set(int x){
    if(father[x]== x)
        return x;
    int p = father[x] ;//递归的求每个结点上面的个数
    father[x] = find_set(father[x]) ;
    up[x] += up[p];
    return father[x];
}
void union_set(int x,int y){
    x =find_set(x);
    y =find_set(y);
    if(x ==y)
        return;
    father[y] =x;
    up[y]=weight[x];
    weight[x]+=weight[y];
}
int main(){
    int p;
    scanf("%d",&p);
    make_set(maxn);
    char str;
    while(p--){
        cin>>str;
        if(str == 'M'){
            int x,y;
            scanf("%d%d",&x,&y);
            union_set(x,y);
        }
        else{
            int x;
            scanf("%d",&x);
            int ans = weight[find_set(x)] - up[x] - 1;
            printf("%d\n",ans);
        }
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值