• HDU 1879 继续畅通工程 (并查集)


    省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。 

    Input测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。 

    当N为0时输入结束。Output每个测试用例的输出占一行,输出全省畅通需要的最低成本。Sample Input

    3
    1 2 1 0
    1 3 2 0
    2 3 4 0
    3
    1 2 1 0
    1 3 2 0
    2 3 4 1
    3
    1 2 1 0
    1 3 2 1
    2 3 4 1
    0

    Sample Output

    3
    1
    0

    TLE,把cin改掉后,过了
     1 #include<cstdio>
     2 #include<iostream>
     3 #include<cmath>
     4 #include<string.h>
     5 #include<algorithm>
     6 #define LL long long
     7 #define N 100001 
     8 using namespace std;
     9 int pre[N];
    10 struct node{
    11     int a, b;
    12     int w;
    13 }road[N];
    14 int fi(int x) {
    15     return pre[x]==x?x:pre[x]=fi(pre[x]);
    16 }
    17 
    18 void uni(int x, int y){
    19     int fx=fi(x), fy=fi(y);
    20     if(fx!=fy){
    21         pre[fx]=fy;
    22     }
    23 }
    24 
    25 bool cmp(node x, node y){
    26     return x.w<y.w;
    27 }
    28 int n;
    29 int main(){
    30     while(scanf("%d",&n)!=EOF){
    31         if(n==0){
    32             break;
    33         }
    34         for(int i=1; i<=n; i++){
    35             pre[i]=i;
    36         }
    37         int sum=0, cnt=0;
    38         for(int i=0; i<n*(n-1)/2; i++){
    39             int a, b, c, d;
    40             scanf("%d%d%d%d",&a,&b,&c,&d);
    41             if(d==1){            
    42                 uni(a,b);
    43             }
    44             else{
    45                 road[cnt].a=a, road[cnt].b=b,road[cnt++].w=c;
    46             }
    47         }
    48         sort(road, road+cnt, cmp);
    49         for(int i=0; i<cnt; i++){
    50             if(fi(road[i].a)!=fi(road[i].b)){
    51                 sum+=road[i].w;
    52                 uni(road[i].a,road[i].b);
    53             }
    54         }
    55         printf("%d
    ",sum);
    56     }
    57 }
  • 相关阅读:
    Awstats显示国家地区插件GeoIP安装 枯木
    springboot_shiro与shiro.ini文件
    Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
    mybatis的dao层xml
    springboot的配置文件
    万事无忧之用泡MM的方式演绎设计模式
    C#设计模式
    软件架构
    什么时候应该使用Web Service
    Spring框架快速入门之简介
  • 原文地址:https://www.cnblogs.com/cake-lover-77/p/10912520.html
Copyright © 2020-2023  润新知