By
yusijia
Updated:
http://acm.hdu.edu.cn/showproblem.php?pid=1233
还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36611 Accepted Submission(s): 16524
Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在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
Sample Output
3
5
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
| #include <cstdio> #include <algorithm> #include <cstring> using namespace std; #define MAXN 10010
int n, m, ans; int father[MAXN]; int ranks[MAXN];
struct Edge{ int from; int to; int cost; }edge[MAXN];
bool cmp(Edge e1, Edge e2) { return e1.cost < e2.cost; }
void init_set() { for(int i = 0; i <= n; i++){ father[i] = i; ranks[i] = 1; } }
int find_set(int x) { return father[x] == x ? father[x] : father[x] = find_set(father[x]); }
void union_set(int x, int y) { if(ranks[x] >= ranks[y]){ ranks[x] += ranks[y]; father[y] = x; } else{ ranks[y] += ranks[x]; father[x] = y; } }
void solve() { init_set(); sort(edge, edge + m, cmp); ans = 0; for(int i = 0; i < m; i++){ int root_x = find_set(edge[i].from); int root_y = find_set(edge[i].to); if(root_x != root_y){ ans += edge[i].cost; union_set(root_x, root_y); } } printf("%d\n", ans); }
int main() { while(scanf("%d", &n) != EOF && n){ m = n* (n - 1) / 2; for(int i = 0; i < m; i++){ scanf("%d%d%d", &edge[i].from, &edge[i].to, &edge[i].cost); } solve(); }
return 0; }
|