- 并查集
——数据结构实验:连通分量个数
#include <iostream>
#include <string.h>
using namespace std;
int n[100010];
int getx(int x) //找节点
{
while(x!=n[x])
{
x=n[x];
}
return x;
}
void hebing(int x,int y) //合并
{
int dx=getx(x);
int dy=getx(y);
if(dx!=dy)
{
n[dx]=dy;
}
}
int main()
{
int a,b,c,d,e,t,i;
cin >> a;
while(a--)
{
t=0;
memset(n,0,sizeof(n));
cin >> b >> c;
for(i=1;i<=b;i++)
{
n[i]=i;
}
while(c--)
{
cin >> d >> e;
hebing(d,e);
}
for(i=1;i<=b;i++)
{
if(n[i]==i)
{
t++;
}
}
cout << t << endl;
}
return 0;
}