#include <iostream>
#include <cstring>
using namespace std;
int Father[1001];
int Rank[1001];
int T;
int N,M;
int sum;
void Make_Set(int x)
{
Father[x] = x;
Rank[x] = 1;
}
int Find(int x)
{
while(x != Father[x])
x = Father[x];
return x;
}
void Union(int x,int y)
{
x = Find(x);
y = Find(y);
if(x == y)
return;
if(Rank[x] < Rank[y])
{
Father[x] = y;
Rank[y] += Rank[x];
}
else
{
Father[y] = x;
Rank[x] += Rank[y];
}
sum --;
}
int main()
{
cin>>T;
while(T--)
{
cin>>N>>M;
int x,y;
sum = N;
for(int i = 1; i <= N; i++)
{
Make_Set(i);
}
for(int i = 1; i <= M; i++ )
{
cin>>x>>y;
Union(x,y);
}
cout<<sum<<endl;
}
return 0;
}
hdu 1213并查集
最新推荐文章于 2019-08-18 12:32:14 发布