显示代码纯文本
//Hawei's Net Bar
//COGS 2253
//Watering Problom
//Hoohan's Program
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int uf[110];
int t,n,m,u,v;
int ans;
int find(int x)
{
int r=x;
while(r!=uf[r]) r=uf[r];
int i=x,j;
while(uf[i]!=r)//zip
{
j=uf[i];
uf[i]=r;
i=j;
}
return r;
}
void mix(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx!=fy)
{
uf[fy]=fx;
}
}
int main()
{
freopen("HWnetbar.in","r",stdin);
freopen("HWnetbar.out","w",stdout);
cin>>t;
for(int i=0;i<t;i++)
{
cin>>n>>m;
//init
ans=0;
for(int i=0;i<=n;i++) {uf[i]=i;}
//input,set up the union find
for(int i=0;i<m;i++)
{
cin>>u>>v;
mix(u,v);
if(find(u)==find(v))
{
mix(u,v);
}
}
for(int i=1;i<=n;i++) ans+=(uf[i]==i);
cout<<ans-1<<endl;
}
return 0;
}