题意:求村镇之间需要多少条路可以联通
思路:求需要多少条路可以联通。这是明显的求并查集的题呀,按照老师上课讲的来,并不是一道难题
感想:无
#include<stdio.h>
#include<iostream>using namespace std;
int bin[1002];
int findx(int x)
{
int r=x;
while(bin[r]!=r)
r=bin[r];
return r;
}
void merge(int x,int y)
{
int fx,fy;
fx = findx(x);
fy = findx(y);
if(fx != fy)
bin[fx]=fy;
}
int main()
{
int n,m,i,x,y,count;
while(cin>>n&&n)
{
for(i=1;i<=n;i++)
bin[i] = i;
cin>>m;
while(m--)
{scanf("%d %d",&x,&y);
merge(x,y);
}
for(count=-1, i=1;i<=n;i++)
if(bin[i]==i)
count++;
printf("%d\n",count);
}
}