畅通工程
简单并查集的应用,模板题
#include<iostream>
#include<cstdio>
using namespace std;
int pre[1100];
int findd(int x)
{
int r=x;
while(r!=pre[r])
{
r=pre[r];
}
int i=x,j;
while(i!=r)
{
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}
void bing (int x,int y)
{
int tx,ty;
tx=findd(x);
ty=findd(y);
if(tx!=ty)
pre[tx]=ty;
}
int main ()
{
int n,m;
while(~scanf("%d",&n))
{
if(n==0)
break;
scanf("%d",&m);
int i;
for(i=1;i<=n;i++)
pre[i]=i;
while(m--)
{
int x,y;
scanf("%d%d",&x,&y);
bing(x,y);
}
int ans=0;
for(i=1;i<=n;i++)
{
if(pre[i]==i)
{
ans++;
}
}
ans--;
printf("%d\n",ans);
}
return 0;
}