传送门:HDU 1213
基础并查集。
#include <iostream>
#include <cstdio>
#define MAX 1005
using namespace std;
int father[MAX];
int Find(int x)
{
if(x==father[x])
return x;
return Find(father[x]);
}
void Union(int x,int y)
{
int xx=Find(x);
int yy=Find(y);
father[xx]=yy;
}
int main()
{
int T,n,m,x,y,i,Count;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
father[i]=i;
for(i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
Union(x,y);
}
for(i=1,Count=0;i<=n;i++)
if(father[i]==i)
Count++;
printf("%d\n",Count);
}
return 0;
}