http://acm.hdu.edu.cn/showproblem.php?pid=1213
。。。好久没写代码了。= =。 非常简单的并查集。
#include <iostream>
using namespace std;
#define N 1003
int people[N];
int findfather(int n){
if (n!=people[n])
people[n]=findfather(people[n]);
return people[n];
}
int main(){
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int t,n,m,i,a,b,sum;
scanf("%d",&t);
while (t--){
scanf("%d%d",&n,&m);
for (i=1;i<=n;i++)
people[i]=i;
while (m--){
scanf("%d%d",&a,&b);
a=findfather(a);
b=findfather(b);
if (a!=b)
people[b]=a;
}
sum=0;
for (i=1;i<=n;i++)
if (people[i]==i)
sum++;
printf("%d\n",sum);
}
return 0;
}