A - How Many Tables
#include<iostream>
using namespace std;
const int maxn = 1050;
int set[maxn];
void init_set()
{
for(int i=0;i<=maxn;++i)set[i]=i;
}
int find_set(int x)
{
return x==set[x]?x:find_set(set[x]);
}
void union_set(int x,int y)
{
x=find_set(x);
y=find_set(y);
if(x!=y)set[x]=set[y];
}
int main()
{
int t,n,m,x,y;
cin>>t;
while(t--)
{
cin>>n>>m;
init_set();
for(int i=1;i<=m;++i)
{
cin>>x>>y;
union_set(x,y);
}
int ans=0;
for(int i=1;i<=n;++i)
{
if(set[i]==i)ans++;
}
cout<<ans<<endl;
}
return 0;
}
优化版,降低了树高
#include<iostream>
using namespace std;
const int maxn = 1050;
int set[maxn],height[maxn];
void init_set()
{
for(int i=0;i<=maxn;++i)
{
set[i]=i;
height[i]=0;
}
}
int find_set(int x)
{
return x==set[x]?x:find_set(set[x]);
}
void union_set(int x,int y)
{
x=find_set(x);
y=find_set(y);
if(height[x]==height[y])
{
height[x]+=1;
set[y]=x;
}
else
{
if(height[x]<height[y])set[x]=y;
else set[y]=x;
}
}
int main()
{
int t,n,m,x,y;
cin>>t;
while(t--)
{
cin>>n>>m;
init_set();
for(int i=1;i<=m;++i)
{
cin>>x>>y;
union_set(x,y);
}
int ans=0;
for(int i=1;i<=n;++i)
{
if(set[i]==i)ans++;
}
cout<<ans<<endl;
}
return 0;
}