HDU-1233 还是畅通工程 (最小生成树)
来源:互联网 发布:hive 数据倾斜 编辑:程序博客网 时间:2024/06/11 05:28
还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 51021 Accepted Submission(s): 23248
Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最小的公路总长度。
Sample Input
31 2 11 3 22 3 441 2 11 3 41 4 12 3 32 4 23 4 50
Sample Output
35Huge input, scanf is recommended.HintHint#include <bits/stdc++.h>using namespace std;struct edge{int from, to, val;bool operator < (const edge& x) const{return val < x.val;}}a[10000];int p[10000];int findset(int x){return p[x] == x ? x : p[x] = findset(p[x]);}int main(){int n, x, y, v;while(scanf("%d", &n) != EOF){if(n == 0) return 0;for(int i = 1; i <= n * (n - 1) / 2; ++i){scanf("%d %d %d", &a[i].from, &a[i].to, &a[i].val);}for(int i = 1; i <= n; ++i){p[i] = i;}sort(a + 1, a + 1 + n * (n - 1) / 2);int tot = 1, pos = 1, ans = 0;while(tot < n){x = findset(a[pos].from);y = findset(a[pos].to);if(x != y){p[x] = y;tot++;ans += a[pos].val;}pos++;}cout << ans << endl;}}/*题意:100个城市,有一些可选择的路,求最小生成树。思路:最小生成树裸题,并查集维护一下两点的连通性。*/
阅读全文