还是畅通工程 (九度 OJ 1017)
1.题目描述:
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政
府“畅通工程的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有
直接的公路相连,只要间接通过公路可达即可),并要求铺设的公路总长度为最
小。请计算最小的公路总长度。
输入:
测试输入包含若干测试用例。每个测试用例的第 1 行给出村庄数目 N ( <
100 );随后的 N(N-1)/2 行对应村庄间的距离,每行给出一对正整数,分别是两
个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从 1 到 N 编号。当 N
为 0 时,输入结束,该用例不被处理。
输出:
对每个测试用例,在 1 行里输出最小的公路总长度。
样例输入:
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
样例输出:
3
5
来源:
2006 年浙江大学计算机及软件工程研究生机试真题
2.基本思路
采用Kruskal算法,对所有的边按照权值进行递增排序,采用并查集的方法实现。
3.代码实现
#include <iostream>
#include <algorithm>
#define N 101
using namespace std;
int Tree[N];
struct Path{
int city1;
int city2;
int cost;
}buf[N*(N-1)/2];
bool cmp(Path p1,Path p2){
return p1.cost<p2.cost;
}
int findRoot(int x){
if(Tree[x]==-1)return x;
else {
int tmp;
tmp = findRoot(Tree[x]);
Tree[x] = tmp;
return tmp;
}
}
int main()
{
int n;
int a,b;
while(scanf("%d",&n)!=EOF){
if(n==0)break;
for(int i=0;i<N;i++){
Tree[i]=-1;
}
for(int i=0;i<n*(n-1)/2;i++){
scanf("%d%d%d",&buf[i].city1,&buf[i].city2,&buf[i].cost);
}
sort(buf,buf+n*(n-1)/2,cmp);
int TotalCost = 0;
for(int i=0;i<n*(n-1)/2;i++){
int rootA = findRoot(buf[i].city1);
int rootB = findRoot(buf[i].city2);
if(rootA!=rootB){//若不在一个集合内
Tree[rootA] = rootB;//把集合A放入B中
TotalCost+=buf[i].cost;
}
}
printf("%d\n",TotalCost);
}
return 0;
}
/*
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
*/