次小生成树。。
思路比较简单,先求出最小生成树,然后枚举每条不在最小生成树上的边(u, v),求u和v路径上的最大边权和次大边权。
如果最大边权和(u, v)的边权相等,那么减去次大边的边权,加上(u, v)的边权,更新答案。
如果最大边权比(u, v)的边权要小,那么减去最大边的边权,加上(u, v)的边权,更新答案。
调了几个小时= =,注意要开LL,而且inf要开大。
/* Pigonometry */
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 100005, maxm = 300005, maxk = 18;
const LL inf = 1LL << 60;
int n, m, head[maxn], cnt, fa[maxn], pre[maxn][maxk], mx[maxn][maxk], sx[maxn][maxk], depth[maxn];
LL sum;
struct _edge {
int v, w, next;
} g[maxn << 1];
struct _spedge {
int u, v, w;
bool operator < (const _spedge &x) const {
return w < x.w;
}
} e[maxm];
inline int iread() {
int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}
inline int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
inline void add(int u, int v, int w) {
g[cnt] = (_edge){v, w, head[u]};
head[u] = cnt++;
}
inline void dfs(int x) {
for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ pre[x][0]) {
depth[g[i].v] = depth[x] + 1;
pre[g[i].v][0] = x;
mx[g[i].v][0] = g[i].w;
dfs(g[i].v);
}
}
inline void update(int &f, int &s, int m1, int s1, int m2, int s2) {
if(m1 > m2) {
f = m1;
if(s1 > m2) s = s1;
else s = m2;
}
else if(m1 < m2) {
f = m2;
if(s2 > m1) s = s2;
else s = m1;
}
else {
f = m1;
if(s2 > s1) s = s2;
else s = s1;
}
}
inline LL calc(int u, int v, int w) {
int f = 0, s = 0;
if(depth[u] < depth[v]) swap(u, v);
for(int i = maxk - 1; i >= 0; i--) if(depth[pre[u][i]] >= depth[v]) {
update(f, s, mx[u][i], sx[u][i], f, s);
u = pre[u][i];
}
for(int i = maxk - 1; i >= 0; i--) if(pre[u][i] != pre[v][i]) {
update(f, s, mx[u][i], sx[u][i], f, s);
u = pre[u][i];
update(f, s, mx[v][i], sx[v][i], f, s);
v = pre[v][i];
}
if(u != v) {
update(f, s, mx[u][0], sx[u][0], f, s);
u = pre[u][0];
update(f, s, mx[v][0], sx[v][0], f, s);
v = pre[v][0];
}
LL res = inf;
if(f == w && s != 0) res = sum - s + w;
else if(w > f) res = sum - f + w;
return res;
}
int main() {
n = iread(); m = iread();
for(int i = 1; i <= m; i++) {
int u = iread(), v = iread(), w = iread();
e[i] = (_spedge){u, v, w};
}
sort(e + 1, e + 1 + m);
for(int i = 1; i <= n; i++) head[i] = -1, fa[i] = i; cnt = 0;
int tot = 0; sum = 0;
for(int i = 1; i <= m && tot != n - 1; i++) {
int u = find(e[i].u), v = find(e[i].v);
if(u != v) {
tot++;
fa[u] = v;
add(e[i].u, e[i].v, e[i].w); add(e[i].v, e[i].u, e[i].w);
sum += e[i].w;
e[i].w = -1;
}
}
dfs(1);
for(int j = 1; j < maxk; j++) for(int i = 1; i <= n; i++) {
update(mx[i][j], sx[i][j], mx[i][j - 1], sx[i][j - 1], mx[pre[i][j - 1]][j - 1], sx[pre[i][j - 1]][j - 1]);
pre[i][j] = pre[pre[i][j - 1]][j - 1];
}
LL ans = inf;
for(int i = 1; i <= m; i++) if(~e[i].w)
ans = min(ans, calc(e[i].u, e[i].v, e[i].w));
printf("%lld\n", ans);
return 0;
}