[2016-01-27][HDU][1233][Constructing Roads]
[2016-01-27][HDU][1233][Constructing Roads]
Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
当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
Hint
Hint Huge input, scanf is recommended.
- 时间:2016-01-21 10:01:56 星期四
- 题目编号:HDU 1233
- 题目大意:
- 给出任意两个城镇的距离,建设公路使之连在一起,求公路总长度最小值
- 方法:
- 直接 kruskal 跑一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | #include <vector>#include <list>#include <map>#include <set>#include <deque>#include <queue>#include <stack>#include <bitset>#include <algorithm>#include <functional>#include <numeric>#include <utility>#include <sstream>#include <iostream>#include <iomanip>#include <cstdio>#include <cmath>#include <cstdlib>#include <cctype>#include <string>#include <cstring>#include <cstdio>#include <cmath>#include <cstdlib>#include <ctime>using namespace std;int n;const int maxn = 110;struct Edge{ int u,v; long long c; bool operator < (const Edge & a)const { return c < a.c; }}e[maxn*maxn/2];int fa[maxn];void ini(){ for(int i = 0;i < n + 5;i++) fa[i] = i;}int fnd(int x){ return x == fa[x] ? x : (fa[x] = fnd(fa[x]));}int kruskal(){ sort(e,e + n*(n-1)/2); int ct = 0; long long res = 0; ini(); for(int i = 0;i < n*(n-1)/2;i++) { if(ct == n - 1) break; int u = e[i].u,v = e[i].v; u = fnd(u); v = fnd(v); if(u != v) { fa[u] = v; res += e[i].c; ct++; } } return res;}int main(){ while(~scanf("%d",&n) && n) { int a,b; long long c; for(int i = 0;i < n*(n-1)/2;i++) { scanf("%d%d%I64d",&a,&b,&c); e[i].u = a; e[i].v = b; e[i].c = c; } long long res = kruskal(); printf("%I64d\n",res); } return 0;} |
浙公网安备 33010602011771号