Out of Hay POJ - 2395

Out of Hay - POJ 2395 - Virtual Judge

看懂题意,其实就是求能形成最小生成树所用的最小的边长值,即最小生成树中最大的边长值最小,Kruskal算法正好对所有边长值进行了排序,因此用Kruskal得出的最小生成树中的最大边长值就是结果

AC代码:

#include <iostream>
#include <queue>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <map>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3f;
int N, M;
int fa[2020];
struct node {
	int from, to, cost;
}edge[10010];
bool cmp(node a, node b) {
	return a.cost < b.cost;
}
int get(int x) {
	return x == fa[x] ? x : fa[x] = get(fa[x]);
}
void solve() {
	cin >> N >> M;
	for (int i = 1; i <= M; i++) {
		cin >> edge[i].from >> edge[i].to >> edge[i].cost;
	}
	sort(edge + 1, edge + 1 + M, cmp);
	for (int i = 1; i <= N; i++) {
		fa[i] = i;
	}
	int ans = 0;
	for (int i = 1; i <= M; i++) {
		int x = get(edge[i].from);
		int y = get(edge[i].to);
		if (x != y) {
			fa[x] = y;
			ans = max(ans, edge[i].cost);
		}
	}
	cout << ans << endl;
	return;
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	solve();
	return 0;
}
/*

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值