打败全网100%人的题解
2026-03-17 20:04:32
发布于:江苏
1阅读
0回复
0点赞
不废话,直接上代码
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 1e5 + 5;
const int M = 2e5 + 5;
const long long oo = 1e18;
int n, m;
int u[M], v[M], w[M], p[M];
int h[N], id[M], nx[M], et;
int f[N], mark[M];
long long s, ans[M];
int dep[N], pid[N];
bool cmp(int x, int y) {
return w[x] < w[y];
}
int getf(int u) {
return f[u] ? f[u] = getf(f[u]) : u;
}
void link(int x, int p) {
id[++et] = p;
nx[et] = h[x];
h[x] = et;
}
void dfs(int x, int f=0, int p=0) {
dep[x] = dep[f] + 1;
pid[x] = p;
for (int i = h[x]; i; i = nx[i]) {
int to = u[id[i]] ^ v[id[i]] ^ x;
if (to != f)
dfs(to, x, id[i]);
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &u[i], &v[i], &w[i]);
p[i] = i;
}
sort(p + 1, p + m + 1, cmp);
for (int i = 1; i <= m; i++) {
int x = u[p[i]], y = v[p[i]];
if (getf(x) == getf(y))
continue;
mark[p[i]] = 1;
f[getf(x)] = y;
s += w[p[i]];
link(x, p[i]);
link(y, p[i]);
}
for (int i = 1; i <= m; i++)
ans[i] = mark[i] ? oo : s;
dfs(1);
for (int i = 1; i <= n; i++)
f[i] = 0;
for (int i = 1; i <= m; i++) {
if (mark[p[i]])
continue;
int x = getf(u[p[i]]), y = getf(v[p[i]]);
while (x != y) {
if (dep[x] < dep[y])
x ^= y ^= x ^= y;
int to = u[pid[x]] ^ v[pid[x]] ^ x;
ans[pid[x]] = s - w[pid[x]] + w[p[i]];
f[x] = to;
x = getf(x);
}
}
for (int i = 1; i <= m; i++)
printf("%lld\n", ans[i] < oo ? ans[i] : -1);
return 0;
}
这里空空如也




有帮助,赞一个