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

HDU 1233 还是畅通工程

时间:2016-01-29 21:00:37      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

还是畅通工程

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 35208    Accepted Submission(s): 15877


Problem 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
Hint
Hint
Huge input, scanf is recommended.
 


Source
 


Recommend

JGShining

 

 

 

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 const int MAX = 150;
 6 int f[MAX];
 7 struct road{
 8     int c1; int c2; int l;
 9 }r[MAX*MAX];
10 
11 bool cmp(const road &r1, const road &r2)
12 {
13     return r1.l<r2.l;
14 }
15 int sf(int x)
16 {
17     return x == f[x] ? x : f[x] = sf(f[x]);
18 }
19 int main()
20 {
21     int n, m, ans,cnt;
22     while (scanf("%d", &n) != EOF&&n)
23     {
24         ans = 0;  cnt = 0;
25         m = n*(n - 1) / 2;
26 
27         for (int i = 1; i <= n; i++)
28             f[i] = i;
29         for (int i = 1; i <= m; i++)
30             scanf("%d%d%d", &r[i].c1, &r[i].c2, &r[i].l);
31         sort(r + 1, r + m + 1, cmp);
32 
33         int i = -1;
34         while (cnt < n - 1)
35         {
36             int q = sf(r[++i].c1);
37             int w = sf(r[i].c2);
38             if (q != w)
39             {
40                 cnt++; f[q] = w; ans += r[i].l;
41             }
42         }
43         printf("%d\n", ans);
44     }
45 }

 

HDU 1233 还是畅通工程

标签:

原文地址:http://www.cnblogs.com/cumulonimbus/p/5169933.html

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