hdu 3635(并查集)

来源:互联网 发布:windows 10家庭版关闭 编辑:程序博客网 时间:2024/05/17 19:23

题目大意:

初始时,有n个龙珠,编号从1到n,分别对应的放在编号从1到n的城市中。

现在有2种操作:

T A B,表示把A球所在城市全部的龙珠全部转移到B球所在城市。

Q A,表示查询A。要求得到的信息分别是:X:A现在所在的城市,Y:A所在城市的龙珠数目,Z:A转移到该城市移动的次数


如果并查集是一种模板,那么这道题一定是要对模板有一定理解才能做的。

所要求的

X:就是求集合的父节点。

Y:带权查询集合内点的个数

Z:本题的精华所在,对深入了解并查集有一定帮助。


其中对于Z,如果每转移一次都要统计该集合内全部的点的情况,那么一定会超时。

那么,我们不得不用到并查集去解决这个问题。这里我们采取路径压缩的方法,开一个辅助数组num,每当龙珠需要转移的时候,将龙珠父节点的num值设为1,并在路径压缩时增加一部操作,使得该点历遍它的父节点时,能递归的求出该点被转移的次数。至此求解完成。


代码如下:

#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>#include <cstring>#include <cstdlib>#include <string>#include <queue>#include <map>#include <vector>using namespace std;char s[10];int father[10005];int sum[10005];int num[10005];int Find(int x){    if(x!=father[x])    {        int t=father[x];        father[x]=Find(father[x]);        num[x]+=num[t];        return father[x];    }    else        return x;}int main(){    int t,n,q,a,b,Case=0;    scanf("%d",&t);    while(t--)    {        scanf("%d %d",&n,&q);        for(int i=1;i<=n;i++)        {            father[i]=i;            sum[i]=1;            num[i]=0;        }        printf("Case %d:\n",++Case);        for(int i=1;i<=q;i++)        {            scanf("%s",s);            if(s[0]=='T')            {                scanf("%d %d",&a,&b);                int f1=Find(a),f2=Find(b);                num[f1]=1;                father[f1]=f2;                sum[f2]+=sum[f1];            }            else            {                scanf("%d",&a);                int qwe=Find(a);                printf("%d %d %d\n",qwe,sum[qwe],num[a]);            }        }    }    return 0;}



0 0
原创粉丝点击