洛谷P2330 [SCOI2005]繁忙的都市 题解 最小生成树的最长边
题目链接:https://www.luogu.com.cn/problem/P2330
这道题其实就是求最小生成树的最长边。
实现代码如下:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010, maxm = 100010;
int n, m, f[maxn], a[maxn];
struct Edge {
int u, v, w;
} edge[maxm];
bool cmp(Edge a, Edge b) {
return a.w < b.w;
}
void init() {
for (int i = 1; i <= n; i ++) f[i] = i;
}
int Find(int x) {
return x == f[x] ? x : f[x] = Find(f[x]);
}
void Union(int x, int y) {
int a = Find(x), b = Find(y);
f[a] = f[b] = f[x] = f[y] = min(a, b);
}
void solve() {
init();
cout << n-1 << " ";
int cnt = 0;
for (int i = 0; i < m; i ++) {
int u = edge[i].u, v = edge[i].v;
if (Find(u) != Find(v)) {
Union(u, v);
cnt ++;
if (cnt == n-1) {
cout << edge[i].w << endl;
break;
}
}
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i ++) cin >> edge[i].u >> edge[i].v >> edge[i].w;
sort(edge, edge+m, cmp);
solve();
return 0;
}