【洛谷】P2330 [SCOI2005] 繁忙的都市 的题解
【洛谷】P2330 [SCOI2005] 繁忙的都市 的题解
题目传送门
题解
水最小生成树,发现可以水一堆黄题qaq
这题显然就是求最大边权最小的生成树,而用 Kruskal 很容易证明这就是最小生成树,考虑一下这个算法每次取的都是不构成环的最小边即可,然后 kruskal + + + 并查集求解。
代码
#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {inline int read() {register int x = 0, f = 1;register char c = getchar();while (c < '0' || c > '9') {if(c == '-') f = -1;c = getchar();}while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();return x * f;}inline void write(int x) {if(x < 0) putchar('-'), x = -x;if(x > 9) write(x / 10);putchar(x % 10 + '0');return;}
}
using namespace fastIO;
int n, m, maxx, sum, fa[10005];
struct node {int u, v, c;
}f[10005];
int find(int x) {return x == fa[x] ? x : fa[x] = find(fa[x]);}
bool cmp (node a, node b) {return a.c < b.c;}
int main() {//freopen(".in","r",stdin);//freopen(".out","w",stdout);ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);cin >> n >> m;for (int i = 1; i <= n; i ++) {fa[i] = i;}for (int i = 1; i <= m; i ++) {cin >> f[i].u >> f[i].v >> f[i].c;}sort (f + 1, f + m + 1, cmp); for (int i = 1; i <= m; i ++) {maxx = f[i].c;if (find(f[i].u) != find(f[i].v)) {sum ++;fa[find(f[i].v)] = find(f[i].u);} else continue;if (sum == n - 1) {break;}}int ans = n - 1;cout << ans << " " << maxx;return 0;
}