【BZOJ3390】[Usaco2004 Dec]Bad Cowtractors牛的报复【最大生成树】

【题目链接】

/* Pigonometry */
#include <cstdio>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 1005, maxm = 20005;

int n, m, fa[maxn];

struct _edge {
	int u, v, w;

	bool operator < (const _edge &x) const {
		return x.w < w;
	}
} g[maxm];

inline int iread() {
	int f = 1; LL x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline int find(int x) {
	return fa[x] == x ? x : fa[x] = find(fa[x]);
}

int main() {
	n = iread(); m = iread();
	for(int i = 1; i <= m; i++) {
		int u = iread(), v = iread(), w = iread();
		g[i] = (_edge){u, v, w};
	}

	sort(g + 1, g + 1 + m);
	for(int i = 1; i <= n; i++) fa[i] = i;

	int cnt = 0; LL ans = 0;
	for(int i = 1; cnt != n - 1 && i <= m; i++) {
		int u = find(g[i].u), v = find(g[i].v);
		if(u != v) {
			cnt++;
			fa[u] = v;
			ans += g[i].w;
		}
	}

	if(cnt != n - 1) ans = -1;
	printf("%lld\n", ans);
	return 0;
}


你可能感兴趣的:(【BZOJ3390】[Usaco2004 Dec]Bad Cowtractors牛的报复【最大生成树】)