带权并查集--hdu3635 Dragon Balls

来源:互联网 发布:自动归类的软件 编辑:程序博客网 时间:2024/05/16 10:21

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 namespacestd;


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];

   }

    returnf[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);

            }

        }

    }

    return0;

}

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

原创粉丝点击