zoukankan      html  css  js  c++  java
  • HDU 1863 畅通工程 (最小生成树)

    畅通工程

    Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 16937    Accepted Submission(s): 7099


    Problem Description
    省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
     
    Input
    测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N 
    行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
     
    Output
    对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
     
    Sample Input
    3 3
    1 2 1
    1 3 2
    2 3 4
    1 3
    2 3 2
    0 100
     
    Sample Output
    3
    ?
     
    Source
     
    Recommend
    lcy
     
    入门最小生成树题目
    Kruskal算法,有贪心的思想在里面
    要记得排序
     1 #include<cstdio>
     2 #include<cstring>
     3 #include<stdlib.h>
     4 #include<algorithm>
     5 using namespace std;
     6 const int MAXN=100+10;
     7 struct node
     8 {
     9     int star;
    10     int en;
    11     int val;
    12     bool operator <(const node &B)const
    13     {
    14         return val<B.val;
    15     }
    16 }a[MAXN];
    17 int p[MAXN];
    18 int Find(int x)
    19 {
    20     return p[x]==x?x:p[x]=Find(p[x]);
    21 }
    22 int main()
    23 {
    24     //freopen("in.txt","r",stdin);
    25     int n,m;
    26     while(scanf("%d %d",&n,&m)&&n)
    27     {
    28         int ans=0,cnt=0;
    29        for(int i=1;i<=n;i++)//输入n条路
    30             scanf("%d %d %d",&a[i].star,&a[i].en,&a[i].val);
    31        sort(a+1,a+n+1);
    32        for(int i=1;i<=m;i++) //村庄的个数
    33             p[i]=i;
    34        for(int i=1;i<=n;i++)//对n条路进行处理
    35        {
    36             int x=Find(a[i].star);
    37             int y=Find(a[i].en);
    38             if(x!=y)
    39             {               
    40                 cnt++;
    41                 ans+=a[i].val; 
    42                 if(cnt==m-1)
    43                     break;
    44                 p[x]=y;
    45             }
    46        }
    47        if(cnt==m-1)
    48             printf("%d
    ",ans);
    49        else
    50             printf("?
    ");
    51     }
    52     return 0;
    53 }
    View Code
  • 相关阅读:
    Avoiding first chance exception messages when the exception is safely handled
    网上邻居解决方法
    ******Can anyone explain me what do you mean by CreateControl
    一個界面設計比較好的外國網站
    How to create a Vertical ProgressBar
    bat如何批量删除指定部分文件夹名的文件夹
    ColumnView.ShownEditor Event
    Apache+php+mysql官方网站下载地址
    根据JAVA的POJO类生成AS3的VALUEOBJECT类
    Spring BlazeDS Integration简介与入门
  • 原文地址:https://www.cnblogs.com/clliff/p/3902923.html
Copyright © 2011-2022 走看看