题目1017:还是畅通工程

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

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

输出:

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

样例输入:
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
样例输出:
3
5
 1 #include <iostream> //1017
 2 #include <algorithm>
 3 #include <set> 
 4 #include <map>
 5 #include <list>
 6 #include <deque>
 7 #include <queue>
 8 #include <stack>
 9 #include <vector>
10 #include <string>
11 #include <fstream>
12 #include <cmath>
13 #include <ctime>
14 #include <cstdio>
15 #include <cctype>
16 #include <cstring>
17 #include <sstream>
18 #include <cstdlib>
19 #include <cassert>
20  
21  
22  
23 using namespace std;
24  
25  
26 struct Node
27 {
28     int u,v;
29     int len;
30 }node[5000]; 
31  
32 int parent[103];
33  
34  
35 bool cmp(Node a,Node b)
36 {
37     if(a.len<b.len)
38         return true;
39     return false;
40 } 
41  
42 int find(int x)
43 {
44     return parent[x] == x? x : find(parent[x]);
45 }
46  
47 int main()
48 {
49     int m;
50     int n;
51     int i;
52     while(cin >> m && m > 0)
53     {
54         int cost = 0;
55         n = m*(m-1)/2;
56          
57         for(i = 1; i <= m; i++)
58             parent[i]=i;
59  
60         for(i = 1; i <= n; i++)
61             cin >> node[i].u >> node[i].v >> node[i].len;
62  
63         sort(node+1,node+1+n,cmp);
64          
65         for(i = 1; i <= n; i++)
66         {
67             int x = find(node[i].u);
68             int y = find(node[i].v);
69             if(x == y)  
70                 continue; 
71             parent[y] = x;
72             cost += node[i].len;
73         }
74          
75         cout<<cost<<endl;
76     }
77     return 0;
78 }

 


posted @ 2013-12-09 20:23  chchche  阅读(205)  评论(0编辑  收藏  举报