POJ 2395 Out of Hay (Kruskal)

题意:从待选的路里面选出若干将所有点连通,求选出的边里最长边的最小值。

算法:要使得树的最长边最小,那么每次确定的边都应是待选边里最小的,即最小生成树。对应Kruskal算法。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;

int N, M; // 农场数,道路数
int par[2005];
void init() {
	for (int i = 1; i <= N; ++i) par[i] = i;
}
int find(int x) {
	return par[x] == x ? x : par[x] = find(par[x]);
}
void unite(int x, int y) {
	x = find(x);
	y = find(y);
	if (x != y) par[x] = y;
}
bool same(int x, int y) {
	return find(x) == find(y);
}
struct edge {
	int u, v, cost;
	edge(int u, int v, int cost) : u(u), v(v), cost(cost) {}
	bool operator<(const edge &b) const {
		return cost < b.cost;
	}
};
vector<edge> es;
void solve() {
	sort(es.begin(), es.end());
	init();
	for (vector<edge>::iterator i = es.begin(); i != es.end(); ++i) {
		if (!same(i->u, i->v)) {
			unite(i->u, i->v);
			N--;
		}
		if (N == 1) { // 第N-1条边
			cout << i->cost << endl;
			break;
		}
	}
}
int main()
{
	cin >> N >> M;
	int u, v, cost;
	for (int i = 0; i < M; ++i) {
		cin >> u >> v >> cost;
		es.push_back(edge(u, v, cost));
	}
	solve();
	return 0;
}
posted @ 2017-08-21 10:35  demianzhang  阅读(307)  评论(0编辑  收藏  举报