题目链接
思路
$$ 最大生成树模板题\\\\注意判断连通性! $$
时间复杂度
$$ O((M)log(M)) $$
代码
#include <cstdio>
#include <algorithm>
#include <vector>
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);
}
};
DSU dsu;
int n, m;
const int MAXN = 2e4 + 10;
int a[MAXN], b[MAXN], c[MAXN], id[MAXN];
bool cmp(int x, int y) {
return c[x] > c[y];
}
int main() {
scanf("%d%d", &n, &m);// don't forget &
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);
long long ans = 0;
for (int i = 1; i <= m; i++) {
int x = id[i];
if (!dsu.same(a[x], b[x])) {
ans += c[x];
dsu.unite(a[x], b[x]);
}
}
int w = dsu.find(1);
for (int i = 1; i <= n; i++) {
if (w != dsu.find(i)) {
ans = -1;
break;
}
}
printf("%lld", ans);
return 0;
}