• HDU 1863 畅通工程(并查集)


    省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。 

    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
    ?

     1 #include<stdio.h>
     2 #include<iostream>
     3 #include<string.h>
     4 #include<algorithm>
     5 #define LL long long
     6 #define N 100001 
     7 using namespace std;
     8 int pre[N];
     9 struct node{
    10     int a, b, w;
    11 }road[N];
    12 int fi(int x) {
    13     return pre[x]==x?x:pre[x]=fi(pre[x]);
    14 }
    15 
    16 void uni(int x, int y){
    17     int fx=fi(x), fy=fi(y);
    18     if(fx!=fy){
    19         pre[fx]=fy;
    20     }
    21 }
    22 
    23 bool cmp(node x, node y){
    24     return x.w<y.w;
    25 }
    26 
    27 int main(){
    28     int n, m;
    29     while(cin>>n){
    30         if(n==0) break;
    31         cin>>m;
    32         for(int i=1; i<=m; i++) {
    33             pre[i]=i;
    34         }
    35         
    36         for(int i=0; i<n; i++){
    37             cin>>road[i].a>>road[i].b>>road[i].w;
    38         }
    39         sort(road, road+n, cmp);
    40         LL sum=0;
    41         for(int i=0; i<n; i++){
    42             if(fi(road[i].a)!=fi(road[i].b)){
    43                 sum+=road[i].w;
    44                 uni(road[i].a, road[i].b);
    45             }
    46         }
    47         int flag=fi(1);
    48         int ff=0;
    49         for(int i=2; i<=m; i++){
    50             if(flag!=fi(i)){
    51                 cout<<"?"<<endl;
    52                 ff=1;
    53                 break;
    54             }
    55         }
    56         if(ff) continue;
    57         cout<<sum<<endl;
    58     }
    59 }
  • 相关阅读:
    微信下载远程图片的公用方法
    微信接口调用
    微信
    post方法
    asp.net pagebase获取缓存的方法
    sql查询最大id
    Controller里写自己需要的Action,参数的名字必须和路由设置的参数名一致

    递归调用
    队列及其应用
  • 原文地址:https://www.cnblogs.com/cake-lover-77/p/10911545.html
Copyright © 2020-2023  润新知