Description
Solution
一道树形dp的题。
首先考虑转移,很简单,就是这个点做不做伐木场。为了方便转移,我们定义状态为\(f_{i,j,k}\)表示点\(i\)及其兄弟的子树中,选了\(k\)个伐木场,且\(j\)是点\(i\)的父亲中距离点\(i\)最近的那个伐木场,这时的总花费。
转移就比较好写了:
\[
f_{i,j,k} = max\{ f_{son_i, j, l} + f_{bro_i, j, k-l} + w_i * dis_{i, j} \} \mbox{(不选i)}\f_{i,j,k} = max\{ f_{son_i, i, l} + f_{bro_i, j, k-l-1} \} \mbox{(选i)}
\]
同时,为了方便这样转移,我们采用左儿子右兄弟法存树。
Code
#include <cstdio>
#include <cstring>
#include <algorithm>
const int N = 100 + 10;
const int M = 2*N;
const int INF = 0x7f7f7f7f;
int ls[N], rs[N], dep[N], w[N], fa[N];
int n, K;
int que[N], tot;
int f[N][N][N];
void dfs(int x, int deep) {
dep[x] += deep;
que[++tot] = x;
int i = ls[x];
while (i) {
dfs(i, dep[x]);
i = rs[i];
}
}
int main() {
memset(fa, -1, sizeof fa);
memset(f, 0x7f, sizeof f);
memset(f[0], 0, sizeof f[0]);
scanf("%d%d", &n, &K);
for (int i = 2, v, d; i <= n+1; ++i) {
scanf("%d%d%d", &w[i], &v, &d);
++v;
rs[i] = ls[v];
ls[v] = i;
dep[i] = d;
fa[i] = v;
}
dfs(1, 0);
for (int i = n+1; i > 1; --i) {
int &x = que[i];
for (int j = fa[x]; j != -1; j = fa[j]) {
for (int k = 0; k <= K; ++k) {
for (int l = 0; l <= k; ++l) { // not choose i
if (f[ls[x]][j][l] < INF && f[rs[x]][j][l] < INF)
f[x][j][k] = std::min(f[x][j][k], f[ls[x]][j][l] + f[rs[x]][j][k-l] + w[x] * (dep[x] - dep[j]));
}
for (int l = 0; l < k; ++l) { // choose i
if (f[ls[x]][x][l] < INF && f[rs[x]][j][k-l-1] < INF)
f[x][j][k] = std::min(f[x][j][k], f[ls[x]][x][l] + f[rs[x]][j][k-l-1]);
}
}
}
}
printf("%d\n", f[ls[1]][1][K]);
return 0;
}
原文地址:https://www.cnblogs.com/wyxwyx/p/ioi2005riv.html
时间: 2024-11-05 22:33:02