带权并查集--hdu3635 Dragon Balls

The first line of the input is a single positive integer T(0 < T <= 100). 
For each case, the first line contains two integers: N and Q (2 < N <= 10000 , 2 < Q <= 10000). 
Each of the following Q lines contains either a fact or a question as the follow format: 
  T A B : All the dragon balls which are in the same city with A have been transported to the city the Bth ball in. You can assume that the two cities are different. 
  Q A : WuKong want to know X (the id of the city Ath ball is in), Y (the count of balls in Xth city) and Z (the tranporting times of the Ath ball). (1 <= A, B <= N)

#include <iostream>

#include <cstdio>

#include <cstring>

using namespace std;


const int maxn = 1e4 + 5;

int f[maxn];

int sz[maxn],trans[maxn];


void init(int n)

{

    for (int i = 1; i <= n; i ++) {

        f[i] = i;

        sz[i] = 1;

        trans[i] = 0;

    }

}

int find(int x)

{

   if(x != f[x])

   {

       int fa = f[x];

       f[x] = find(fa);

       trans[x] += trans[fa];

   }

    return f[x];

}

void merge(int x,int y)

{

    x = find(x);

    y = find(y);

    if(x == y) return;

    sz[y] += sz[x];

    trans[x] ++;

    f[x] = y;

}

void query(int x)

{

    int fx = find(x);

    printf("%d %d %d\n",fx,sz[fx],trans[x]);

}

int main()

{

    int T;cin >> T;

    int n,q;

    char op;

    int a,b;

    for(int cn = 1;cn <= T;cn ++) {

        scanf("%d%d%*c",&n,&q);

        init(n);

        printf("Case %d:\n",cn);

        for (int i = 0; i < q; i ++) {

            scanf("%c",&op);

            if(op == 'T'){

                scanf("%d%d%*c",&a,&b);

                merge(a,b);

            }

            else{

                scanf("%d%*c",&a);

                query(a);

            }

        }

    }

    return 0;

}

//带权并查集,一般在find(int x)都会在压缩路径的同时更新权值,写的时候要注意。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值