码迷,mamicode.com
首页 > 其他好文 > 详细

并查集压缩hdu2818

时间:2015-07-27 16:28:41      阅读:82      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!