AcWing 10. 有依赖的背包问题

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 110;
int n,m;
int w[N],v[N],root;
int h[N],e[N],ne[N],idx;
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 = v[u]; i <= m; ++i) f[u][i] = w[u];
    for(int i = h[u]; ~i; i = ne[i]) {
        int son = e[i];
        dfs(son);
        for(int j = m; j >= v[u]; --j) {
            for(int k = 0 ; k <= j - v[u]; ++k) {
                f[u][j] = max(f[u][j],f[u][j - k] + f[son][k]);
            }
        }
    }
}
int main() {
    #ifdef ONLINE_JUDGE
    #else
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif // ONLINE_JUDGE
    cin>>n>>m;
    int p;
    memset(h,-1,sizeof(h));
    for(int i = 1; i <= n; ++i) {
        cin>>v[i]>>w[i]>>p;
        if(p == -1) root = i;
        else add(p,i);
    }
    dfs(root);
    cout<<f[root][m]<<endl;
    return 0;
}
posted @ 2022-02-22 14:29  lemonsbiscuit  阅读(36)  评论(0编辑  收藏  举报