mxda13530175581
笔记
记录一下
38行k遍历的是son节点在不同体积下的价值,把son节点不同体积看成分组下的每个元素;
49行不能是f[u][j] = max(f[u][j], f[u][j - v[u]] + w[u]),是应为f[u][j]代表不选的的情况,而u节点默认是一定选的;
54行,如果root条件不满足,那么它的子节点满足也没用(应为选了子节点就要选它的根节点),所以直接在当前节点置零
C++ 代码
#include<iostream>
#include<cstring>
using namespace std;
const int N = 110;
int h[N], e[N], ne[N], idx;
int n, m;
int v[N], w[N];
int f[N][N];
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
void dfs(int u)
{
for (int i = h[u]; i != -1; i = ne[i])
{
int son = e[i];
dfs(son);
for (int j = m - v[u]; j >= 0; j -- )
{
for (int k = 0; k <= j; k ++ )
{
f[u][j] = max(f[u][j], f[u][j - k] + f[son][k]);
}
}
}
for (int j = m; j >= v[u]; j -- )
{
f[u][j] = f[u][j - v[u]] + w[u];
}
for (int j = 0; j < v[u]; j ++ )
{
f[u][j] = 0;
}
}
int main()
{
int root, a, b, c;
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 1; i <= n; i ++ )
{
cin >> a >> b >> c;
v[i] = a, w[i] = b;
if (c == -1)
{
root = i;
}
else
{
add(c, i);
}
}
dfs(root);
cout << f[root][m];
return 0;
}