有依赖背包存在多棵树的情况
作者:
想不出来_6
,
2024-02-27 17:20:46
,
所有人可见
,
阅读 42
有依赖背包存在多棵树的情况,直接将0节点加入树中
#include <iostream>
#include <cstring>
using namespace std;
const int N = 111;
int n, m, root;
int h[N], e[N], ne[N], idx;
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; 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()
{
memset(h, -1, sizeof h);
cin >> n >> m;
root = 0;
for (int i = 1; i <= n; ++ i)
{
int p;
cin >> v[i] >> w[i] >> p;
if (p == -1) add(root, i);
else add(p, i);
}
dfs(root);
cout << f[root][m] << endl;
return 0;
}