首页 > 其他 > 详细

并查集压缩hdu2818

时间:2015-07-27 16:27:27      阅读:215      评论:0      收藏:0      [点我收藏+]
#include<cstdio>
#include<algorithm>
using namespace std;
int root[30010];
int num1[30010];
int num2[30010];
int find2(int x)
{
    if(x != root[x])
    {
        int fx  = root[x];
        root[x]  = find2(fx);
        num1[x] +=  num1[fx];
    }
    return root[x];
}
void Union(int a,int b)
{
    int fa = find2(a);
    int fb = find2(b);
    if(fa != fb)
    {
        root[fa] = fb;
        num1[fa] = num2[fb] + 1;
        num2[fb] += num2[fa] + 1;
    }
}
int main()
{
    for(int i=1;i<=30000;i++) root[i]=i;
    int p;
    scanf("%d",&p);
    while(p--)
    {
        char c;
        scanf("%*c%c",&c);
        if(c == 'M'){
            int a,b;
        scanf("%d%d",&a,&b);
            Union(a,b);
        }
        else {
            int d;
        scanf("%d",&d);
            find2(d);
            printf("%d\n",num1[d]);

//        for(int i=1;i<=10;i++)
//            printf("%d ",num1[i]); printf("\n");
        }
    }
    return 0;
}
开了3个数组,要仔细想

版权声明:本文为博主原创文章,未经博主允许不得转载。

并查集压缩hdu2818

原文:http://blog.csdn.net/a197p/article/details/47085077

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!