HDU 2818 Building Block (并查集)

15 篇文章 0 订阅
Problem Description
John are playing with blocks. There are N blocks (1 <= N <= 30000) numbered 1...N。Initially, there are N piles, and each pile contains one block. Then John do some operations P times (1 <= P <= 1000000). There are two kinds of operation:

M X Y : Put the whole pile containing block X up to the pile containing Y. If X and Y are in the same pile, just ignore this command. 
C X : Count the number of blocks under block X 

You are request to find out the output for each C operation.
 

Input
The first line contains integer P. Then P lines follow, each of which contain an operation describe above.
 

Output
Output the count for each C operations in one line.
 

Sample Input
  
  
6 M 1 6 C 1 M 2 4 M 2 6 C 3 C 4
 

Sample Output
  
  
1 0 2
 

本题题目的意思是:Farmer John 和 Betsy 在玩一种游戏:堆箱子。其中有两种操作:一种是移动,由字母‘M’表示;另一种是输出,由字母‘C’表示。

即:

1、M   X   Y 是表示:把含X 的那一叠箱子按照原来的顺序全部堆到含y 的那一叠箱子的最上面;

2、C   X 是表示:计算含X 的箱子下面有几个箱子,并输出。

这些箱子是一条直线的往上叠。

思路:找到含X的那叠箱子的箱子总是减去X上面的箱子数再减去一就是所要的答案。

 

明白几点:如果a堆在b上,那么b上面的箱子数就是等于含a的那叠箱子的总数;

b那叠箱子总数就为a的总数加上原来b的箱子总数。

还要注意在路径压缩的时候对num_up数组的更新:

num_up[x]+=num_up[tmp];//该节点x头上的节点个数等于其父节点头上的加上自己原本头上的

这里用递归:可以这样理解:把x点头上的每个点相加



#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int num[330000];
int set[330000];
int under[330000];
int find(int x)
{
    int tmp;
    if (x!=set[x])
    {
        tmp = find(set[x]);
        under[x] += under[set[x]];
        set[x] = tmp;
    }
    return set[x];
	
}
void merge(int a,int b)
{
    int fx=find(a);
    int fy=find(b);
    if(fx!=fy)
    {
        under[fx]=num[fy];
        num[fy]+=num[fx];
        set[fx]=fy;
    }
}
int main()
{
    int n,a,b;
    char s[5];
    while(scanf("%d",&n)!=EOF)
    {
        memset(under,0,sizeof(under));
        for(int i=0; i<=n; i++)//初始化
        {
            set[i]=i;
            num[i]=1;
        }
        for(int i=0; i<n; i++)
        {
            cin>>s;
            if(s[0]=='M')
            {
                cin>>a>>b;
                merge(a,b);
            }
            else
            {
                cin>>a;
                find(a);
                printf("%d\n",under[a]);
            }
        }
    }
    return 0;
} 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值