bzoj 3390: [Usaco2004 Dec]Bad Cowtractors牛的报复 — 最大生成树

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

Time Limit: 1 Sec  Memory Limit: 128 MB

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

HINT

#include<map>
#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
#define N 1010
#define M 20010
inline int rd()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
struct qaz{int a,b;ll v;}e[M];
bool cmp(qaz a,qaz b){return a.v>b.v;}
int cnt,fa[N];
int findf(int x){return x==fa[x]?x:fa[x]=findf(fa[x]);}
int n,m,x,y;
ll ans;
int main()
{
    n=rd();m=rd();
    int i,j,f1,f2;
    for(i=1;i<=n;i++) fa[i]=i;
    for(i=1;i<=m;i++){e[i].a=rd();e[i].b=rd();e[i].v=rd();}
    sort(e+1,e+m+1,cmp);
    for(int i=1;i<=m;i++)
    {
        x=findf(e[i].a);y=findf(e[i].b);
        if(x!=y)
        {
            ans+=e[i].v;
            fa[y]=x;
        }
    }
    bool f=0;x=findf(1);
    for(int i=1;i<=n;i++) if(findf(i)!=x){f=1;break;}
    f?puts("-1"):printf("%lld\n",ans);
    return 0;
}

评论

还没有任何评论,你来说两句吧

发表评论

衫小寨 出品