带权并查集- Building Block (HDU - 2818)

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

题意:存在两种操作,M 操作和 C 操作;

1.M a b 操作:将a所在的块(就是a所在的那一堆) 全部堆到 b(所在的那一堆上)。

2.C a 操作:计算a下面有多少个块。

由样例可知操作:M 1 6,M 2 4后的得到如图  且根设置为 6  和 4;故而 fa[1] = 6,fa[2] = 4; cnt[4] = 2,cnt[6] = 2;

再经过 M 2 6后可知

此时的4号 下面 是原先的 6号集合 故num[4]的值为cnt[6],fa[4] = 6.

所以当查找 2 号下的所有点时,递归路线为  2 -----> 4 -----> 6;

num[2] += (num[4]+=num[6]); 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 3e4+5;
int fa[maxn],num[maxn],cnt[maxn]; //cnt记录每个集合的个数,num记录下面块的个数
int findfa(int x)
{
    if(x == fa[x])
        return x;
    int temp = findfa(fa[x]); 
    num[x] += num[ fa[x] ]; //递归时不断的更新经过点的值
    return fa[x] = temp;
}
void Union(int a,int b)
{
    int x = findfa(a),y = findfa(b);
    if(x != y)
    {
        fa[x] = y; 
        num[x] = cnt[y]; //该跟结点下全是下面的节点
        cnt[y] += cnt[x]; //统计该集合所有点的个数
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    char c;
    int a,b;
    for(int i = 0; i < maxn; i++)
    {
        fa[i] = i;
        cnt[i] = 1;
    }
    memset(num,0,sizeof num);
    while(T--)
    {
        cin>>c;
        if(c == 'C')
        {
            scanf("%d",&a);
            findfa(a);
            cout<<num[a]<<endl;
        }
        else
        {
            scanf("%d%d",&a,&b);
            Union(a,b);
        }
    }
    return 0;
}
/*
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4

*/

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值