kuangbin_UnionFind C (HDU 1213)

时间:2024-01-02 00:03:21

过程模板 扫一下一共有几棵树 输出

#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#define MAX 1010
using namespace std;
int father[MAX],table[MAX];
int Findfather(int x)
{
while(x!=father[x])
x=father[x];
return x;
}
void Union(int x,int y)
{
x=Findfather(x);
y=Findfather(y);
father[x]=y;
}
int main()
{
int t,n,m,count;
scanf("%d",&t);
while(t--)
{
count=;
scanf("%d%d",&n,&m);
for(int i=;i<=n;i++)
{
father[i]=i;
table[i]=;
}
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
Union(a,b);
}
for(int i=;i<=n;i++)
{
int tmp=Findfather(i);
bool same=false;
for(int j=;j<=count;j++)
if(tmp==table[j])
{
same=true;
break;
}
if(!same){
table[++count]=tmp;
}
}
printf("%d\n",count);
}
return ;
}