HDU 1213(并查集,father total)

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

#include<bits/stdc++.h>
using namespace std;
#define maxn 1100
int father[maxn];
int n,m;

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

猜你喜欢

转载自blog.csdn.net/beposit/article/details/80616937