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

hdu 1213 How Many Tables(并查集求无向图有几个连通分量)

时间:2015-07-24 22:46:06      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:并查集

代码:

#include<cstdio>
#include<cstring>
using namespace std;

int n,m;
int father[1005];

int Find(int a)
{
    int r=a;
    while(father[a]!=a)
    {
        a=father[a];
    }
    father[r]=a;
    return a;
}

void Union(int a,int b)
{
    a=Find(a);
    b=Find(b);
    if(a!=b)
        father[b]=a;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int ans=0;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            father[i]=i;
        }
        for(int i=1;i<=m;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            Union(a,b);
        }
        for(int i=1;i<=n;i++)
        {
            father[i]=Find(i);
            if(father[i]==i)
                ans++;
        }
        printf("%d\n",ans);
    }
    return 0;
}


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

hdu 1213 How Many Tables(并查集求无向图有几个连通分量)

标签:并查集

原文地址:http://blog.csdn.net/xky1306102chenhong/article/details/47046653

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!