zoukankan      html  css  js  c++  java
  • 洛谷 P1546 最短网络 Agri-Net Label:Water最小生成树

    题目背景

    农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。

    题目描述

    约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。

    你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000

    输入输出格式

    输入格式:

    第一行: 农场的个数,N(3<=N<=100)。

    第二行..结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。

    输出格式:

    只有一个输出,其中包含连接到每个农场的光纤的最小长度。

    输入输出样例

    输入样例#1:
    4
    0 4 9 21
    4 0 8 17
    9 8 0 16
    21 17 16 0
    输出样例#1:
    28

    说明

    题目翻译来自NOCOW。

    USACO Training Section 3.1

    代码

     1 #include<iostream>
     2 #include<cstring>
     3 #include<cstdio>
     4 #include<algorithm>
     5 #include<vector>
     6 #include<queue>
     7 #define MAXN 20000
     8 using namespace std;
     9 
    10 struct cc{
    11     int from,to,cost;
    12 }e[50000];
    13 
    14 bool cmp(cc a,cc b){
    15     return a.cost<b.cost;
    16 }
    17 
    18 int fa[999],N,map[999][999],p,ans,cnt;
    19 
    20 int Find(int x){
    21     if(fa[x]==x)return x;
    22     else return fa[x]=Find(fa[x]);
    23 }
    24 void unite(int a,int b){
    25     int ta=Find(a),tb=Find(b);
    26     if(ta==tb) return;
    27     fa[ta]=tb;
    28 }
    29 
    30 
    31 int main(){
    32 //    freopen("01.in","r",stdin);
    33     scanf("%d",&N);
    34     for(int i=1;i<=N;i++){
    35         for(int j=1;j<=N;j++){
    36             scanf("%d",&map[i][j]);
    37         }
    38     }
    39     for(int i=1;i<=N;i++){
    40         for(int j=i+1;j<=N;j++){
    41             e[++p].cost=map[i][j];
    42             e[p].from=i;
    43             e[p].to=j;
    44         }
    45     }
    46     for(int i=1;i<=N;i++) fa[i]=i;
    47     sort(e+1,e+p+1,cmp);
    48     for(int i=1;i<=p;i++){
    49         cc x=e[i];
    50         if(Find(x.from)==Find(x.to)) continue;
    51         unite(x.from,x.to);
    52         if(cnt>=N-1) break;
    53         ++cnt;
    54         ans+=x.cost;
    55     }
    56     printf("%d
    ",ans);
    57     return 0;
    58 }
    版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
  • 相关阅读:
    POJ 1141 括号匹配 DP
    881. Boats to Save People
    870. Advantage Shuffle
    874. Walking Robot Simulation
    文件操作
    861. Score After Flipping Matrix
    860. Lemonade Change
    842. Split Array into Fibonacci Sequence
    765. Couples Holding Hands
    763. Partition Labels
  • 原文地址:https://www.cnblogs.com/radiumlrb/p/6034106.html
Copyright © 2011-2022 走看看