HDU1213-How Many Tables

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

并查集第一题

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int fa[1010];
int find(int x)
{
    if(fa[x])  
       return fa[x]=find(fa[x]);  
    return x;  
}
int main(void)
{
    int n,m,x,y,t,ans,i;
    cin>>t;
       while(t--) 
       {
           memset(fa,0,sizeof(fa));
        cin>>n>>m;
        while(m--) 
        {
            cin>>x>>y;
            x=find(x);
            y=find(y);
            if(x!=y)
               fa[x]=y;
         }
           ans=0;
           for(i=1;i<=n;i++)
              if(!fa[i])         
                 ans++;
           cout<<ans<<endl;
       }
    return 0;
}
posted @ 2012-08-30 21:01  Yogurt Shen  阅读(95)  评论(0编辑  收藏  举报