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; } /* */
Out of Hay POJ - 2395
最新推荐文章于 2024-10-08 20:32:22 发布