# 树形背包学习笔记

## $n^3$解法

### 原理

$$f[u][i]=max(f[u][j]+f[v][i-j]+d[v])\ [j=1...i-1]$$

### 例题

Luogu P2014 选课

#include <cstdio>
#include <algorithm>
using std::max;

const int N = 3e2 + 10, M = 3e2 + 10;
int n, m, f[N][N], s[N], son[N][N];

void dfs (int u) {
for (int i = 1; i <= son[u][0]; ++i) {
int v = son[u][i]; dfs(v);
for (int j = m + 1; j >= 1; --j)
for (int k = 0; k < j; ++k)
f[u][j] = max(f[u][j], f[u][j - k] + f[v][k]);
}
}

int main () {
scanf ("%d%d", &n, &m);
for (int i = 1, fa; i <= n; ++i) {
scanf ("%d%d", &fa, s + i);
f[i][1] = s[i];
son[fa][++son[fa][0]] = i;
}
dfs(0);
printf ("%d\n", f[0][m + 1]);
return 0;
}


## $n^2$解法

### 原理

1.选取当前节点：

$$f[i+1][j+1]=f[i][j]+d[i]$$

2.不选当前节点：

$$f[nx[i]][j]=f[i][j]$$

### 例题

#include <cstdio>
#include <algorithm>
using std::min;
typedef long long ll;

const int N = 3e2 + 10, M = 3e2 + 10, Inf = 1e9 + 7;
int n, m, d[N], s[N], dfn[N], son[N][N], time, f[N][N], nx[N];
inline void upt (int &a, int b) { if(a < b) a = b; }

void Init_dfs(int u) {
dfn[u] = time++;
for (int i = 1; i <= son[u][0]; ++i)
Init_dfs(son[u][i]);
nx[dfn[u]] = time;
}

void Doit_dp() {
for (int i = 1; i <= n; ++i)
d[dfn[i]] = s[i];
for (int i = 1; i <= n + 1; ++i)
for (int j = 0; j <= m; ++j)
f[i][j] = -Inf;
for (int i = 0; i <= n; ++i)
for (int j = 0; j <= min(i, m); ++j) {
upt(f[i + 1][j + 1], f[i][j] + d[i]);
upt(f[nx[i]][j], f[i][j]);
}
}

int main () {
scanf("%d%d", &n, &m); ++m;
for (int i = 1, fa; i <= n; ++i) {
scanf("%d%d", &fa, s + i);
son[fa][++son[fa][0]] = i;
}
Init_dfs(0);//预处理dfs
Doit_dp();//动态规划
printf("%d\n", f[n + 1][m]);
return 0;
}


// luogu-judger-enable-o2
#include <cstdio>
#include <algorithm>
using std::min;
using std::max;

const int N = 3e3 + 10, inf = 1e9 + 7;
const double eps = 1e-5;
int n, K, s[N], p[N], son[N][N], dfn[N], time, nx[N];
int from[N], to[N], nxt[N], cnt;//Edges
double f[N][N], d[N];

inline void addEdge (int u, int v) {
to[++cnt] = v, nxt[cnt] = from[u], from[u] = cnt;
}

inline void upt(double &a, double b) {
if (a < b) a = b;
}

void dfs (int u) {
dfn[u] = time++;
for (int i = from[u]; i; i = nxt[i]) dfs(to[i]);
nx[dfn[u]] = time;
}

inline bool check (double k) {
for (int i = 1; i <= n; ++i)
d[dfn[i]] = p[i] - k * s[i];
for (int i = 1; i <= n + 1; ++i)
for (int j = 0; j <= K; ++j)
f[i][j] = -inf;
for (int i = 0; i <= n; ++i)
for (int j = 0; j <= min(i, K); ++j) {
upt(f[i + 1][j + 1], f[i][j] + d[i]);
upt(f[nx[i]][j], f[i][j]);
}
return f[n + 1][K] >= eps;
}

int main () {
scanf("%d%d", &K, &n); ++K;
for (int i = 1, fa; i <= n; ++i)  {
scanf("%d%d%d", s + i, p + i, &fa);
addEdge(fa, i);
}
dfs(0);
double l = 0, r = 10000, ans;
while (r - l >= eps) {
double mid = (l + r) * 0.5;
if (check(mid)) ans = mid, l = mid + eps;
else r = mid - eps;
}
printf ("%.3lf\n", ans);
return 0;
}

posted @ 2018-10-19 20:31  water_mi  阅读(1064)  评论(2编辑  收藏