BZOJ4033 [HAOI2015]T1

时间:2023-01-12 21:58:41

令$f[p][i]$表示以$p$为根的子树内,选了$i$个黑点,剩下的都是白点的这个子树内贡献的答案

如果$p$的子树都算出来了,只要计算$p$与$fa[p]$之间的边对答案的贡献就好了,贡献是$dis * (i * (sz - i) + (k - i) * (n - k - (sz - i)))$

于是树形动规一下就好了

 /**************************************************************
Problem: 4033
User: rausen
Language: C++
Result: Accepted
Time:308 ms
Memory:32300 kb
****************************************************************/ #include <cstdio>
#include <cstring>
#include <algorithm> using namespace std;
typedef long long ll; const int N = 2e3 + ; struct edge {
int next, to, v;
edge(int _n = , int _t = , int _v = ) : next(_n), to(_t), v(_v) {}
} e[N << ]; int n, k;
int first[N], tot;
int sz[N];
ll f[N][N], tmp[N]; inline void Add_Edges(int x, int y, int z) {
e[++tot] = edge(first[x], y, z), first[x] = tot;
e[++tot] = edge(first[y], x, z), first[y] = tot;
} inline ll calc(int x, int y) {
return 1ll * y * (x - y);
} #define y e[x].to
inline void dfs(int p, int fa, int w) {
int x, i, j;
sz[p] = ;
for (x = first[p]; x; x = e[x].next)
if (y != fa) {
dfs(y, p, e[x].v);
memcpy(tmp, f[p], sizeof(tmp));
for (i = min(sz[p], k); ~i; --i)
for (j = min(sz[y], k - i); ~j; --j)
tmp[i + j] = max(tmp[i + j], f[p][i] + f[y][j]);
memcpy(f[p], tmp, sizeof(tmp));
sz[p] += sz[y];
}
for (i = min(sz[p], k); ~i; --i)
f[p][i] += (calc(k, i) + calc(n - k, sz[p] - i)) * w;
}
#undef y int main() {
int i, x, y, z;
scanf("%d%d", &n, &k);
for (i = ; i < n; ++i) {
scanf("%d%d%d", &x, &y, &z);
Add_Edges(x, y, z);
}
dfs(, , );
printf("%lld\n", f[][k]);
return ;
}