Hoj 2385 Cube Stacking

题目:http://acm.hit.edu.cn/hoj/problem/view?id=2385

并查集的巧妙应用,注意是多组测试数据,Poj上相同一题是一组测试数据。

开一个数组deep,表示这个结点离根结点的距离,每次移动的时候,只需要更新一次要放上去的立方体的个数,就是移动后该结点到根结点的距离。查询的时候,只需要用总数-离根结点的距离然后-1即可。

注意findset()更新时deep的顺序。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
using namespace std;

int father[30005];
int son[30005];
int deep[30005];

int findset(int a)
{
    if(a == father[a])
    {
        return a;
    }
    //注意顺序
    int temp = father[a];
    father[a] = findset(temp);
    deep[a] += deep[temp];

    return father[a];

}


int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    int p;

    while(scanf(" %d",&p)!=EOF)
    {
        for(int i=1; i<30005; i++)
        {
            father[i] = i;
            son[i] = 1;
            deep[i] = 0;
        }
        char c;
        int x,y;
        for(int i=0; i<p; i++)
        {
            scanf(" %c",&c);
            if(c == 'M')
            {
                scanf(" %d %d",&x,&y);
                x = findset(x);
                y = findset(y);
                if(x!=y)
                {
                    father[y] = x;
                    //顺序不要颠倒
                    deep[y] = son[x];
                    son[x] += son[y];
                }
            }
            else if(c == 'C')
            {
                int d;
                scanf(" %d",&d);
                printf("%d\n",son[findset(d)] - deep[d] - 1);
            }
        }
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值