hdu 3635 Dragon Balls(带权并查集)

来源:互联网 发布:航天开票软件开票流程 编辑:程序博客网 时间:2024/04/29 19:30

Dragon Balls

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=3635

解题思路:

题目大意:

初始时,有n个龙珠,编号从1到n,分别对应的放在编号从1到n的城市中。
给你2种操作:
T A B,表示把A球所在城市全部的龙珠全部转移到B城市。(第一次时,因为A球所在的城市只有一个球,所以只移动1个,如果有多个,则全部移动)。
Q A,表示查询A。输出信息。信息分别为:A现在所在的城市,A所在城市的龙珠数目,A转移到该城市移动的次数(如果没有移动就输出0)。

算法思想:

并查集操作即可,处理好子节点与父亲结点的关系就行了。。。

AC代码:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn = 10005;int pa[maxn],num[maxn],t[maxn];int findset(int x){    if(x == pa[x])        return x;    int p = pa[x];    pa[x] = findset(pa[x]);    t[x] += t[p];    return pa[x];}int main(){    int T,tt = 1;    scanf("%d",&T);    while(T--){        int n,m;        scanf("%d%d",&n,&m);        for(int i = 1; i <= n; i++){            pa[i] = i;            num[i] = 1;            t[i] = 0;        }        char op;        int x,y;        printf("Case %d:\n",tt++);        for(int i = 0; i < m; i++){            getchar();            scanf("%c",&op);            if(op == 'T'){                scanf("%d%d",&x,&y);                x = findset(x);                y = findset(y);                if(x != y){                    pa[x] = y;                    num[y] += num[x];                    t[x]++;                }            }            else{                scanf("%d",&x);                y = findset(x);                printf("%d %d %d\n",y,num[y],t[x]);            }        }    }    return 0;}


0 0