题意
Sol
首先一个很显然的思路是直接用(f[i][j] / g[i][j])表示(i)的子树中选了(j)个节点,该节点是否选的最小权值。但是直接这样然后按照树形背包的套路转移的话会有一种情况无法处理,就是说该节点不选,儿子节点也不选,这样我们就不清楚儿子节点的子节点的贡献了
一种暴力的做法是钦定该节点选,并重新枚举子树中的所有节点,转移出dp值之后背包合并
最后再把(0)号节点的合并一次
#include<bits/stdc++.h>
#define chmin(x, y) (x = x < y ? x : y)
#define chmax(x, y) (x = x > y ? x : y)
using namespace std;
const int MAXN = 1001, INF = 2e9 + 10;
inline int read() {
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int N, K, a[MAXN], dis[MAXN], siz[MAXN], f[MAXN][MAXN], g[MAXN][MAXN], ans;
vector<int> v[MAXN];
void dfs2(int x, int fa, int root) {
f[x][0] = dis[root] * a[x];
for(int i = 0; i < v[x].size(); i++) {
int to = v[x][i]; if(to == fa) continue;
dfs2(to, x, root);
for(int j = min(K, siz[x]); ~j; j--)
for(int k = 0; k <= min(j, siz[to]); k++)
chmax(f[x][j], f[to][k] + f[x][j - k]);
}
for(int i = siz[x]; i; i--) chmax(f[x][i], g[x][i]);
}
void dfs(int x, int fa) {
dis[x] += dis[fa]; siz[x] = 1;
for(int i = 0; i < v[x].size(); i++) {
int to = v[x][i];
if(to == fa) continue;
dfs(to, x); siz[x] += siz[to];
}
g[x][0] = 0;
memset(f, 0, sizeof(f));
for(int i = 0; i < v[x].size(); i++) {
int to = v[x][i]; if(to == fa) continue;
dfs2(to, x, x);
for(int j = min(K, siz[x]); ~j; j--)
for(int k = 0; k <= min(j, siz[to]); k++)
chmax(g[x][j], f[to][k] + g[x][j - k]);
}
for(int i = min(K, siz[x]); i; i--) g[x][i] = g[x][i - 1] + dis[x] * a[x];
}
int main() {
N = read(); K = read();
for(int i = 1; i <= N; i++) {
a[i] = read(); int fa = read(); dis[i] = read();
v[fa].push_back(i);
}
dfs(0, -1);
for(int i = 1; i <= N; i++) ans += dis[i] * a[i];
memset(f, 0, sizeof(f));
int x = 0;
for(int i = 0; i < v[x].size(); i++) {
int to = v[x][i];
dfs2(to, x, x);
for(int j = min(K, siz[x]); ~j; j--)
for(int k = 0; k <= min(j, siz[to]); k++)
chmax(f[x][j], f[to][k] + f[x][j - k]);
}
int out = INF;
for(int i = 0; i <= K; i++) out = min(out, ans - f[0][i]);
printf("%d
", out);
return 0;
}