zoukankan      html  css  js  c++  java
  • [HDOJ1233]还是畅通工程

    还是畅通工程

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


    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
     
    并查集+最小生成树,使用STL的优先队列(STL优先队列介绍:http://blog.csdn.net/morewindows/article/details/6976468)
    注意数组开大点,代码如下:
     
     1 #include <iostream>
     2 #include <queue>
     3 #include <cstdio>
     4 #include <cstring>
     5 #define MAXN 100000
     6 
     7 using namespace std;
     8 
     9 int pre[MAXN];
    10 struct Node {
    11     int x;
    12     int y;
    13     int d;
    14     friend bool operator < (Node a, Node b) {
    15         return a.d > b.d;
    16     }
    17 };
    18 
    19 int find(int x) {
    20     return x == pre[x] ? x : pre[x] = find(pre[x]);
    21 }
    22 
    23 int unite(int x, int y) {
    24     x = find(x);
    25     y = find(y);
    26     if(x != y) {
    27         pre[x] = y;
    28         return 1;
    29     }
    30     return 0;
    31 }
    32 
    33 int main() {
    34     int N, n, ans;
    35     while(~scanf("%d", &N) && N != 0) {
    36         ans = 0;
    37         n = N * (N - 1) / 2;
    38         priority_queue<Node> q;
    39         Node tmp;
    40         for(int i = 1; i <= n; i++) {
    41             scanf("%d %d %d", &tmp.x, &tmp.y, &tmp.d);
    42             pre[i] = i;
    43             q.push(tmp);
    44         }
    45         N = N - 1;
    46         while(N) {
    47             tmp = q.top();
    48             q.pop();
    49             if(unite(tmp.x, tmp.y)) {
    50                 N--;
    51                 ans += tmp.d;
    52             }
    53         }
    54         printf("%d
    ", ans);
    55     }
    56     return 0;
    57 }
    View Code
  • 相关阅读:
    MagicAjax简单介绍(转)
    .net中RegisterStartupScript与RegisterClientScriptBlock的区别
    改变你一生的五句话 (转)
    苏州园林年卡 办理与使用 附 苏州园林门票价格
    常见的 ASP.NET 2.0 转换问题和解决方案(转)
    .net新手须知
    AJAX开发简略 (转)
    magicajax为什么不能提交? magicajax的一个bug
    所谓:有实际开发工作经验 (转)
    解读60 70 80年代职场人
  • 原文地址:https://www.cnblogs.com/kirai/p/4607549.html
Copyright © 2011-2022 走看看