码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1233 还是畅通工程 (最小生成树)

时间:2015-08-17 21:51:06      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

hdu 1233 还是畅通工程

Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。

Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。

Output
对每个测试用例,在1行里输出最小的公路总长度。

Sample Input

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

Sample Output

3
5

题目大意:中文题。

解题思路:最小生成树。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;

const int N = 1005;
const int M = 25005;
typedef long long ll;
int n;
int fa[N], cnt;
struct Node{
    int a, b, len;
}p[M];

void init() {
    cnt = 0;
    for (int i = 0; i <= n; i++) {
        fa[i] = i;  
    }
}

int cmp(Node x, Node y) {
    return x.len < y.len;
}

int find(int x) {
    return x == fa[x] ? x : fa[x] = find(fa[x]);
}

int kruskal() {
    sort(p, p + cnt, cmp);
    double ans = 0;
    for (int i = 0; i < cnt; i++) {
        int x = find(p[i].a), y = find(p[i].b);
        if (x != y) {
            fa[x] = y;
            ans += p[i].len;
        }
    }
    return ans;
}

void input() {
    for (int i = 0; i < n * (n - 1) / 2; i++) {
        scanf("%d %d %d", &p[cnt].a, &p[cnt].b, &p[cnt].len);
        cnt++;
    }
}

int main() {
    while (scanf("%d", &n) != EOF) {
        if (!n) break;  
        init();
        input();
        printf("%d\n", kruskal());
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不可转载。

hdu 1233 还是畅通工程 (最小生成树)

标签:

原文地址:http://blog.csdn.net/llx523113241/article/details/47731777

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!