hdu1213 How Many Tables 并查集

#include<iostream>
#include<cstdio>
#define Maxn 1024
int father[Maxn];
void init(int n)
{   for(int i=1;i<=n;i++)
    father[i]=i;
}
int getf(int x)
{   if(x!=father[x])
    father[x]=getf(father[x]);
    return father[x];


}
void union2(int x,int y)
{   x=getf(x);
    y=getf(y);
    if(x!=y)
    father[x]=y;
}


int main()
{   int T;
    scanf("%d",&T);
    while(T--)
    {   int n,m,ans=0;
        scanf("%d%d",&n,&m);
        init(n);
        for(int i = 0 ;i<m;i++)
        {int x,y;
        scanf("%d%d",&x,&y);
        union2(x,y);
        }
        for(int i=1;i<=n;i++)
        {if(father[i]==i)
            ans++;
        }
        printf("%d\n",ans);




    }
    return 0;
}


你可能感兴趣的:(hdu1213 How Many Tables 并查集)