Problem Description原题目链接
某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。
为简单起见,城镇从1到N编号。
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的 当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最少还需要建设的道路数目。
#include<vector>
#include<iostream>
using namespace std;
class UF
{
private:
vector<int> s;
public:
int find(int x);
void unionUF(int root1,int root2);
UF(int n):s(n, -1){};
};
//使用路径压缩
int UF::find(int x) {
if(s[x]<0)
return x;
else
return s[x] = find(s[x]);
}
//按秩合并
void UF::unionUF(int root1,int root2){
if(s[root2] < s[root1]) //因为是负值,说明root2更深
s[root1] = root2;
else {
if(s[root1] == s[root2])
--s[root1]; //高度加1
s[root2] = root1;
}
}
int main(){
int N,M,total;
int x,y; //当前读入的路的两个端点
cout<<"请输入城镇数目N,及城镇道路数目M,M为0程序结束"<<endl;
while(scanf("%d%d",&N,&M)&&N) //读入n,如果n为0,结束
{
total=N-1; //刚开始的时候,有n个城镇,一条路都没有,那么要修n-1条路才能把它们连起来
UF uf(N);
while(M--){
scanf("%d%d",&x,&y);
while(x<1 || y<1 || x>N || y> N){
cout<<"x,y必须大于1,小于N"<<endl;
scanf("%d%d",&x,&y);
}
//如果输入的边还没有连通,那么把他们连起来,此时需要修的路也少了一条
if(uf.find(x-1) != uf.find(y-1)){
uf.unionUF(x-1,y-1);
total--;
}
}
printf("%d\n",total);
}
}
复制代码