题目意思:
某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
算法:并查集呀!!!
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int N,M;
int L,S;//较大较小的城市
int city[1000];
int find(int l)
{
if(city[l]==l)return l;
else return find(city[l]);
}
int main()
{
//freopen("1232.txt","r",stdin);
int i,ans;
while(~scanf("%d",&N),N)
{
scanf("%d",&M);
ans=0;
for(i=1;i<=N;i++)
city[i]=i;
for(i=1;i<=M;i++)
{
scanf("%d%d",&L,&S);
L=find(L);
S=find(S);
city[L]=S;
}
for(i=1;i<=N;i++)
{
if(city[i]==i)ans++;
}
printf("%d\n",ans-1);
}
return 0;
}