hdu-1213-How Many Tables

来源:互联网 发布:中国没艺术家 知乎 编辑:程序博客网 时间:2024/06/17 09:33

题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1213


并查集算法,推荐博客(点击“博客”两字)。

推荐类似题目:

  1.  poj-1258-Agri-Net 
  2. hdu-1232-畅通工程
  3. hdu-1863-畅通工程

#include <iostream>#include<algorithm>#include<cstring>#include<cstdio>#include<stack>#include<queue>using namespace std;int a[1005];int bing(int x){    if(a[x]==x) return x;    a[x]=bing(a[x]);    return a[x];}int main(){    int t;    cin>>t;    while(t--)    {        int m,n;;        cin>>m>>n;        for(int i=1; i<=m; i++)        {            a[i]=i;        }        for(int i=1; i<=n; i++)        {            int x,y;            cin>>x>>y;            int xx=bing(x),yy=bing(y);            if(xx!=yy)            {                a[yy]=xx;            }        }        int ans=0;        for(int i=1; i<=m; i++)        {            if(a[i]==i) ans++;        }        cout<<ans<<endl;    }    return 0;}


原创粉丝点击