POJ 2377 Bad Cowtractors(kruskal最大生成树)

题目就是求最大生成树,用kruskal算法乱搞一下就好了,

要注意一下生成树不存在的时候要输出-1。。

#pragma warning(disable:4996)
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

struct edge {
	int from, to, cost;
	bool operator<(const edge &op)const {
		return cost > op.cost;
	}
};

edge e[20005];
int fa[1005], n, m;

int find(int x) {
	if (x == fa[x])return x;
	return fa[x] = find(fa[x]);
}

int kruskal() {
	for (int i = 1; i <= n; i++)fa[i] = i;
	int ret = 0, cnt = 1;
	sort(e, e + m);
	for (int i = 0; i < m; i++) {
		int x = find(e[i].from);
		int y = find(e[i].to);
		if (x != y) {
			fa[x] = y;
			ret += e[i].cost;
			cnt++;
		}
	}
	if (cnt < n)ret = -1;
	return ret;
}

int main() {
	scanf("%d %d", &n, &m);
	for (int i = 0; i < m; i++) {
		scanf("%d %d %d", &e[i].from, &e[i].to, &e[i].cost);
	}
	printf("%d\n", kruskal());
	return 0;
}


你可能感兴趣的:(POJ 2377 Bad Cowtractors(kruskal最大生成树))