被同学强迫写了这个题。邪恶的随机化,太神秘了。
首先可以做一个非常朴素简单的 dp: 表示 子树内,选了若干条长为 的链,和一条长为 的起点为 的链的最优价值,条件是它们两两边不相交。
这个东西的转移是这样:显然得拿一些 或者 加上 的边拼起来,也可能是 直接连上 的边。
所以令 表示考虑了前几个儿子 ,选择 的比 的多 个, 的个数的奇偶性为 的最大价值。
这里转移看起来是 的。然后就上了一个神秘的随机化。
我们考虑最终的决策,如果把儿子随机打乱,再把决策对应到随机序列上,每一个 看做 , 看做 ,那么这个东西在原 dp 式子上面的 就是这个随机正负 序列的前缀绝对最大值了,这东西 ,所以 random_shuffle 完就是对的了。
然后我还莫名其妙拿了个最优解。怎么回事呢。
#include <bits/stdc++.h>
#define int long long
#define fs first
#define sc second
using namespace std;
using pii = pair<int, int>;
struct ios {
inline char read() {
static const int inlen = 1 << 18 | 1;
static char buf[inlen], *s, *t;
return (s == t) && (t = (s = buf) + fread(buf, 1, inlen, stdin)), s == t ? -1 : *s++;
}
template<typename T> inline ios& operator>> (T &x) {
static char c11, boo;
for (c11 = read(), boo = 0; !isdigit(c11); c11 = read()) {
if (c11 == -1) return *this;
boo |= c11 == '-';
}
for (x = 0; isdigit(c11); c11 = read()) x = x * 10 + (c11 ^ '0');
boo && (x = -x);
return *this;
}
} fin;
struct exios {
template<typename _CharT, typename _Traits = char_traits<_CharT>>
struct typ {
typedef basic_ostream<_CharT, _Traits>& (* end) (basic_ostream<_CharT, _Traits>&);
};
template<typename T> friend exios &operator<<(exios &out, T num) {
if (num < 0) putchar('-'), num = -num;
if (num >= 10) out << num / 10;
putchar(num % 10 + '0');
return out;
}
friend exios &operator<<(exios &out, const char * s) { printf("%s", s); return out; }
friend exios &operator<<(exios &out, string s) { cout << s; return out; }
friend exios &operator<<(exios &out, typ<char>::end e) { puts(""); return out; }
} fout;
const int maxn = 2e5 + 10;
const int maxb = 5e2 + 10;
const int B = 5e2;
int n;
vector<pii> tr[maxn];
int f[maxn][4], g[maxb << 1][2], h[maxb << 1][2];
void dfs(int u, int fa) {
vector<pii> sn;
for (pii e : tr[u]) {
int v = e.fs;
if (v == fa) continue;
dfs(v, u), sn.push_back(e);
}
random_shuffle(sn.begin(), sn.end());
memset(g, -0x3f, sizeof(g)), memset(h, -0x3f, sizeof(h));
int L = B, R = B;
g[L][0] = h[L][0] = 0;
int up = (sn.size() + 1) / 2;
for (pii e : sn) {
int v = e.fs, w = e.sc;
L = max(max(-up + B, 1ll), L - 1), R = min(min(up + B, B * 2), R + 1);
for (int i = L; i <= R; i++) {
for (int j = 0; j <= 1; j++) {
g[i][j] = h[i][j] + f[v][0];
g[i][j] = max(g[i][j], h[i][j] + w + f[v][3]);
g[i][j] = max(g[i][j], h[i - 1][j] + w + f[v][0]);
g[i][j] = max(g[i][j], h[i + 1][j] + w + f[v][2]);
g[i][j] = max(g[i][j], h[i][j ^ 1] + w + f[v][1]);
}
}
for (int i = L; i <= R; i++)
for (int j = 0; j <= 1; j++)
h[i][j] = g[i][j];
}
f[u][0] = g[B][0], f[u][1] = g[B + 1][0], f[u][2] = g[B][1], f[u][3] = g[B - 1][0];
}
signed main() {
srand(time(0));
fin >> n;
for (int i = 1, u, v, w; i < n; i++) {
fin >> u >> v >> w;
tr[u].push_back({v, w});
tr[v].push_back({u, w});
}
dfs(1, 0);
fout << f[1][0] << endl;
return 0;
}