zoukankan      html  css  js  c++  java
  • BZOJ 3390: [Usaco2004 Dec]Bad Cowtractors牛的报复

    题目

    3390: [Usaco2004 Dec]Bad Cowtractors牛的报复

    Time Limit: 1 Sec  Memory Limit: 128 MB
    Submit: 53  Solved: 37
    [Submit][Status]

    Description

        奶牛贝茜被雇去建设N(2≤N≤1000)个牛棚间的互联网.她已经勘探出M(1≤M≤
    20000)条可建的线路,每条线路连接两个牛棚,而且会苞费C(1≤C≤100000).农夫约翰吝啬得很,他希望建设费用最少甚至他都不想给贝茜工钱. 贝茜得知工钱要告吹,决定报复.她打算选择建一些线路,把所有牛棚连接在一起,让约翰花费最大.但是她不能造出环来,这样约翰就会发现.

    Input

      第1行:N,M.
      第2到M+1行:三个整数,表示一条可能线路的两个端点和费用.
     

    Output

     
        最大的花费.如果不能建成合理的线路,就输出-1

    Sample Input

    5 8
    1 2 3
    1 3 7
    2 3 10
    2 4 4
    2 5 8
    3 4 6
    3 5 2
    4 5 17

    Sample Output

    42

    连接4和5,2和5,2和3,1和3,花费17+8+10+7=42

    题解

    这道题目就是最大生成树!-1的情况就是无法组成一棵树的情况。

    代码

     1 /*Author:WNJXYK*/
     2 #include<cstdio>
     3 #include<algorithm> 
     4 using namespace std;
     5 const int Maxn=1000;
     6 int father[Maxn+10];
     7 inline void initFather(){
     8     for (int i=1;i<=Maxn;i++) father[i]=i;
     9 }
    10 
    11 inline int getFather(int x){
    12     return father[x]=father[x]==x?x:getFather(father[x]);
    13 }
    14 
    15 inline void mergeFather(int x,int y){
    16     int lx=getFather(x),ly=getFather(y);
    17     if (lx<ly){
    18         father[ly]=lx;
    19     }else{
    20         father[lx]=ly;
    21     }
    22 } 
    23 
    24 struct Edge{
    25     int x,y;
    26     int w;
    27     Edge(){}
    28     Edge(int a,int b,int c){
    29         x=a;
    30         y=b;
    31         w=c;
    32     }
    33 };
    34 
    35 const int Maxm=20000;
    36 Edge e[Maxm+10];
    37 
    38 bool cmp(Edge a,Edge b){
    39     if (a.w>b.w) return true;
    40     return false;
    41 }
    42 
    43 int cnt,ans; 
    44 
    45 int n,m;
    46 int main(){
    47     scanf("%d%d",&n,&m);
    48     initFather();
    49     for (int i=1;i<=m;i++){
    50         int x,y,z;
    51         scanf("%d%d%d",&x,&y,&z);
    52         e[i]=Edge(x,y,z);
    53     }
    54     sort(e+1,e+m+1,cmp);
    55     cnt=n;
    56     for (int i=1;i<=m;i++){
    57         int x=e[i].x,y=e[i].y,w=e[i].w;
    58         if (getFather(x)!=getFather(y)){
    59             mergeFather(x,y);
    60             cnt--;
    61             ans+=w;
    62         }
    63         if (cnt==1) break;
    64     }
    65     if (cnt!=1){
    66         printf("-1
    ");
    67         return 0;
    68     }
    69     printf("%d
    ",ans);
    70     return 0;
    71 }
    View Code
  • 相关阅读:
    C#的默认访问权限
    隐藏基类成员
    索引指示器的重载
    索引指示器
    vector
    string 函数
    细胞个数
    计蒜客 T1096 石头剪刀布
    计蒜客 T1125 判断字符串是否为回文
    计蒜客 T1152 成绩排序
  • 原文地址:https://www.cnblogs.com/WNJXYK/p/4070212.html
Copyright © 2011-2022 走看看