【BZOJ】3390: [Usaco2004 Dec]Bad Cowtractors牛的报复(kruskal)

http://www.lydsy.com/JudgeOnline/problem.php?id=3390

。。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define for1(i,a,n) for(int i=(a);i<=(n);++i)
#define for2(i,a,n) for(int i=(a);i<(n);++i)
#define for3(i,a,n) for(int i=(a);i>=(n);--i)
#define for4(i,a,n) for(int i=(a);i>(n);--i)
#define CC(i,a) memset(i,a,sizeof(i))
#define read(a) a=getint()
#define print(a) printf("%d", a)
#define dbg(x) cout << #x << " = " << x << endl
#define printarr2(a, b, c) for1(i, 1, b) { for1(j, 1, c) cout << a[i][j]; cout << endl; }
#define printarr1(a, b) for1(i, 1, b) cout << a[i]; cout << endl
inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; }
inline const int max(const int &a, const int &b) { return a>b?a:b; }
inline const int min(const int &a, const int &b) { return a<b?a:b; }
 
const int N=20005;
int p[N], n, m, ans;
struct ED { int x, y, w; }e[N];
bool cmp(const ED &a, const ED &b) { return a.w>b.w; }
const int ifind(const int &x) { return x==p[x]?x:p[x]=ifind(p[x]); }
 
int main() {
	read(n); read(m);
	for1(i, 1, m) read(e[i].x), read(e[i].y), read(e[i].w);
	sort(e+1, e+1+m, cmp);
	int tot=0;
	for1(i, 1, n) p[i]=i;
	for1(i, 1, m) {
		int fx=ifind(e[i].x), fy=ifind(e[i].y);
		if(fx!=fy) {
			p[fx]=fy;
			ans+=e[i].w;
			++tot;
		}
	}
	if(tot<n-1) puts("-1");
	else print(ans);
	return 0;
}

 

 


 

 

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

posted @ 2014-09-18 13:38  iwtwiioi  阅读(211)  评论(0编辑  收藏  举报