说明
某市调查城镇交通状况,得到现有城镇道路统计表。表中列出了每条道路直接连通的城镇。市政府 "村村通工程" 的目标是使全市任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要相互之间可达即可)。请你计算出最少还需要建设多少条道路?
输入格式
输入包含若干组测试数据,每组测试数据的第一行给出两个用空格隔开的正整数,分别是城镇数目n和道路数目m(输入n=0表示测试数据结束);随后的m行对应m条道路,每行给出一对用空格隔开的正整数,分别是该条道路直接相连的两个城镇的编号。简单起见,城镇从1到n编号。
注意:两个城市间可以有多条道路相通。
对于 100% 的数据,保证 1≤n<1000 。
输出格式
对于每组数据,对应一行一个整数。表示最少还需要建设的道路数目。
样例
输入数据 1
4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
Copy
输出数据 1
1
0
2
998
并查集的模板题
思路:
这道题我们把使用题目给出的道路,将两个不同城市合并为一个城市,并记录合并城市的次数(即减少城市的数量,下面代码中的 ans ),最后我们只要判断现在还有多少个家族让后减一(两个家族需要修一条道路)即可!
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
using namespace std;
#define ll long long
int n=1,m,p,ans=0;
int fa[1000];
void init(int mm) {
for(int i=1; i<=mm; i++)
fa[i]=i;
}
int find(int x) {
int temp=x;
while(x!=fa[x])
x=fa[x];
while(temp!=fa[temp]) {
int bf=fa[temp];
fa[temp]=x;
temp=bf;
}
return x;
}
void merge(int a,int b) {
int aa=find(a);
int bb=find(b);
if(aa!=bb) {
ans++;
fa[bb]=aa;
}
}
int main() {
while(n) {
scanf("%d",&n);
if(!n) break;
ans=0;
scanf("%d",&m);
init(n);
for(int i=1; i<=m; i++) {
int a,b;
scanf("%d%d",&a,&b);
merge(a,b);
}
cout<<n-ans-1<<endl;
}
return 0;
}