题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1213
并查集算法,推荐博客(点击“博客”两字)。
推荐类似题目:
#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;
}