zoukankan      html  css  js  c++  java
  • hdoj 1233 还是畅通工程

    还是畅通工程

    原题链接:https://acm.hdu.edu.cn/showproblem.php?pid=1233

    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

    根据边权值排序道路,然后根据并查集来判断是不是成一个环

     1 #include <queue> 
     2 #include <stdio.h>
     3 
     4 using namespace std;
     5 const int maxn=100+1;
     6 int father[maxn];
     7 
     8 struct edge{
     9     int src, dest, cost;
    10     bool operator <(const edge & nxt) const {
    11         return cost>nxt.cost;
    12     }
    13 };
    14 void init(int n){
    15     for (int i=1;i<=n;i++){
    16         father[i]=i;
    17     }
    18 }
    19 
    20 int find(int a){
    21     int x=a;
    22     while(a!=father[a]){
    23         a=father[a];
    24     }
    25     while(x!=father[x]){
    26         int tmp=x;
    27         x=father[x];
    28         father[tmp]=a;
    29     }
    30     return a;
    31 }
    32 
    33 bool Union(int a , int b){
    34     int x1=find(a);
    35     int x2=find(b);
    36     if (x1!=x2){
    37         father[x1]=x2;
    38         return true;
    39     }else return false;
    40 }
    41 
    42 int main(){
    43     edge e;
    44     int n,m;
    45     while(scanf("%d",&n)!=EOF && n ) {
    46         priority_queue<edge> q;
    47         init(n);
    48         m=n*(n-1)/2;
    49         while(m--){
    50             scanf("%d%d%d", &e.src, &e.dest, &e.cost);
    51             q.push(e);
    52         }
    53         int ans=0,count=0;
    54         while(!q.empty()){
    55             e=q.top();
    56             q.pop();
    57             if(Union(e.src,e.dest)){ //并查集来判断是不是成环 
    58                 count++;
    59                 ans+=e.cost;
    60             }
    61             if(count==n-1) break; 
    62         }
    63         printf("%d
    ",ans);
    64     }
    65     return 0;
    66 }
  • 相关阅读:
    LF Filed Control
    《C++反汇编与逆向分析技术揭秘》——流程控制语句的识别
    《C++反汇编与逆向分析技术揭秘》——观察各种表达式的求值过程
    项目笔记---图片处理
    项目笔记---压缩方式
    Visual Studio 使用调试技巧
    温故知新---重读C#InDepth(二)
    温故知新---重读C#InDepth(一)
    SQL笔记---多表左联
    SQL笔记---分页
  • 原文地址:https://www.cnblogs.com/z-712/p/15125757.html
Copyright © 2011-2022 走看看