题目链接
思路
$$ 最小生成树基础题 $$
时间复杂度
$$ O((M)log(M)) $$
代码
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
class DSU {
public:
vector<int> p, r;
void init(int n) {
p.resize(n + 10);
r.resize(n + 10);
for (int i = 0; i <= n; i++) {
p[i] = i;
r[i] = 0;
}
}
int find(int x) {
if (x == p[x]) {
return x;
} else {
return p[x] = find(p[x]);
}
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
if (r[x] < r[y]) {
p[x] = y;
} else {
p[y] = x;
if (r[x] == r[y]) {
r[x]++;
}
}
return true;
}
bool same(int x, int y) {
return find(x) == find(y);
}
};
const int MAXN = 1e4 + 10;
int a[MAXN], b[MAXN], c[MAXN], id[MAXN];
bool cmp(int x, int y) {
return c[x] < c[y];
}
int main() {
int n, m;
scanf("%d%d", &n, &m);// don't forget &
DSU dsu;
dsu.init(n);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &a[i], &b[i], &c[i]);// don't forget &
id[i] = i;
}
sort(id + 1, id + 1 + m, cmp);
int ans = 0;
for (int i = 1; i <= m; i++) {
int x = id[i];
if (!dsu.same(a[x], b[x])) {
dsu.unite(a[x], b[x]);
ans = max(ans, c[x]);
}
}
printf("%d", ans);
return 0;
}