(step6.1.5)hdu 1233(还是畅通工程——最小生成树)

时间:2022-10-08 00:58:46

题目大意:输入一个整数n,表示有n个村庄,在接下来的n*(n-1)/2中,每行有3个整数beigin、end、weight,分别表示路的起始村庄,结束村庄和村庄之间的距离。

求索要修的路的最短距离

解题思路:最小生成树(克鲁斯卡尔算法实现)。。。

PS:更详细的说明在上一篇博客中有

代码如下:

/*
* 1233_1.cpp
*
* Created on: 2013年8月26日
* Author: Administrator
*/ #include <iostream> using namespace std; struct edge{
int begin;
int end;
int weight;
}; const int maxn = 6000;
int father[maxn];
edge e[maxn*maxn]; int find(int x){
if( x == father[x]){
return x;
} father[x] = find(father[x]);
return father[x];
} int kruscal(int count){
int i;
int sum = 0; for( i = 1 ; i < maxn ; ++i){
father[i] = i;
} for( i = 0 ; i < count ; ++i ){
int fx = find(e[i].begin);
int fy = find(e[i].end); if(fx != fy){
father[fx] = fy;
sum += e[i].weight;
}
} return sum;
} bool compare(const edge& a , const edge& b){
return a.weight < b.weight;
} int main(){
int n;
while(scanf("%d",&n)!=EOF,n){
int i;
int m = n*(n - 1)/2;
memset(father,0,sizeof(father));//尽量加上,否则可能会出现一些问题 for(i = 0; i < m ; ++i){
scanf("%d%d%d",&e[i].begin,&e[i].end,&e[i].weight);
} sort(e, e + m , compare); int sum = kruscal(m); printf("%d\n",sum);
}
}