并查集的模板题目
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int maxn = 1000+10;
int father[maxn];
int getfather(int fx)
{
int x = fx;
while(x != father[x])
return father[x] = getfather(father[x]);
return father[x];
}
void merge(int a, int b)
{
int fa = getfather(a);
int fb = getfather(b);
if (fa != fb)
{
father[fb] = fa;
}
}
int main(int argc, char const *argv[])
{
int ncase;
scanf("%d", &ncase);
while(ncase--)
{
int n,m;
int ans = 0;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i)
{
father[i] = i;
}
for (int i = 1; i <= m; ++i)
{
int a,b;
scanf("%d%d",&a,&b);
merge(a,b);
}
for (int i = 1; i <= n; ++i)
{
if (i == father[i])
{
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}