社区讨论
WA50 求调
P14080[GESP202509 八级] 最小生成树参与者 4已保存回复 4
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 4 条
- 当前快照
- 1 份
- 快照标识符
- @mhj3xzlk
- 此快照首次捕获于
- 2025/11/03 20:19 4 个月前
- 此快照最后确认于
- 2025/11/03 20:19 4 个月前
rt。
CPP/*
Code by swate114514.
*/
#include <bits/stdc++.h>
using namespace std;
using i32 = int32_t;
using i64 = int64_t;
using ui32 = uint32_t;
using ui64 = uint64_t;
using PII = pair<int, int>;
int _;
namespace swate {
inline int read() {int s = 0, w = 1; char ch = getchar();while (ch < '0' || ch > '9') {if (ch == '-') w *= -1;ch = getchar();}while (ch >= '0' && ch <= '9') {s = (s << 3) + (s << 1) + (ch ^ 48);ch = getchar();}return s * w;}
inline i64 read2() {i64 s = 0, w = 1; char ch = getchar();while (ch < '0' || ch > '9') {if (ch == '-') w *= -1;ch = getchar();}while (ch >= '0' && ch <= '9') {s = (s << 3) + (s << 1) + (ch ^ 48);ch = getchar();}return s * w;}
inline void write(int x) {if (x < 0) x = -x, putchar('-');if (x > 9) write(x / 10);putchar(x % 10 + '0');}
const int N = 1e5 + 5;
int n, m, pa[N];
bool vis[N];
struct node {
int u, v;
i64 w;
int id;
bool operator < (const node& x) {
return w < x.w;
}
} a[N];
inline void init() {
}
inline int find(int x) {
return x == pa[x] ? x : pa[x] = find(pa[x]);
}
inline void kruskal(i64& ans, int p) {
int cnt = 0;
for (int i = 1; i <= n; ++i) {
pa[i] = i;
}
for (int i = 1; i <= m; ++i) {
if (a[i].id == p) {
continue;
}
int x = find(a[i].u), y = find(a[i].v);
if (x == y) continue;
pa[x] = y;
if (p == 0) {
vis[a[i].id] = 1;
}
ans += a[i].w;
cnt++;
if (cnt == n - 1) {
return ;
}
}
if (cnt == n - 1) {
return ;
}
ans = -1;
}
inline void solve() {
n = read(), m = read();
for (int i = 1; i <= m; ++i) {
a[i] = {read(), read(), read2(), i};
}
i64 ans = 0;
sort(a + 1, a + m + 1);
kruskal(ans, 0);
if (ans == -1) {
for (int i = 1; i <= m; ++i) {
write(-1), putchar('\n');
}
} else {
for (int i = 1; i <= m; ++i) {
if (!vis[i]) {
write(ans), putchar('\n');
} else {
i64 nw = 0;
kruskal(nw, i);
write(nw), putchar('\n');
}
}
}
}
}
//#define Test
i32 main() {
#ifdef Test
cin >> _;
#else
_ = 1;
#endif
for (int i = 1; i <= _; ++i) {
swate::init();
swate::solve();
}
return 0;
}
回复
共 4 条回复,欢迎继续交流。
正在加载回复...