您的位置:首页 > 其它

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

2015-10-25 10:57 363 查看

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

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 127  Solved: 77

[Submit][Status][Discuss]

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

Source

Silver

题解:最大生成树,不解释。

代码:

<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#define ll long long
#define N 1005
#define M 20005
using namespace std;
int read()
{
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 Node{
int x,y,val;
}a[M];
int n,m,f
;
ll ans=0;
bool cmp(Node a,Node b){return a.val>b.val;}
int find(int x){return f[x]==x?x:f[x]=find(f[x]);}
int main()
{
n=read();m=read();
for(int i=1;i<=m;i++)
{
a[i].x=read();a[i].y=read();a[i].val=read();
}
sort(a+1,a+1+m,cmp);
for(int i=1;i<N;i++)f[i]=i;
int sum=0;
for(int i=1;i<=m;i++)
{
Node now=a[i];
int fx=find(now.x),fy=find(now.y);
if(fx!=fy)
{
ans+=now.val;sum++;
f[fx]=fy;
}
if(sum==n-1)break;
}
if(sum<n-1)cout<<"-1"<<endl;
else cout<<ans<<endl;
}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: