HDU 1561 The more, The Better 树形dp 有依赖的背包问题

https://vjudge.net/problem/HDU-1561
在这里插入图片描述思路:稍微转化一下就是有依赖的背包问题了,当然也属于树形 d p dp 的范畴。这里就说一下怎么转化,认为每一个城堡的体积都是 1 1 ,背包的总体积为 m m 即可,当然有个细节要注意,就是点 0 0 的体积是 0 0
关于有依赖的背包问题,可以看我这篇博客的介绍:
https://blog.csdn.net/xiji333/article/details/104226993

#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;

const int maxn=205;

struct Edge
{
    int to,nxt;
}edge[maxn];

int n,m,tot;
int head[maxn],val[maxn],dp[maxn][maxn];

inline void addedge(int u,int v)
{
    edge[++tot].to=v,edge[tot].nxt=head[u],head[u]=tot;
}

void dfs(int u)
{
    int v;
    int w=1;
    if(u==0)
        w=0;
    for(int i=head[u];i;i=edge[i].nxt)
    {
        v=edge[i].to;
        dfs(v);
        for(int j=m-w;j>=1;j--)
            for(int k=j;k>=1;k--)
                dp[u][j]=max(dp[u][j],dp[u][j-k]+dp[v][k]);
    }
    for(int i=m;i>=w;i--)
        dp[u][i]=dp[u][i-w]+val[u];
}

int main()
{
    while(~scanf("%d%d",&n,&m)&&(n!=0||m!=0))
    {
        tot=0;
        memset(head,0,sizeof(head));
        memset(dp,0,sizeof(dp));
        int t;
        for(int i=1;i<=n;i++)
        {
            scanf("%d%d",&t,&val[i]);
            addedge(t,i);
        }
        dfs(0);
        printf("%d\n",dp[0][m]);
    }
    return 0;
}

发布了677 篇原创文章 · 获赞 30 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/104719289
今日推荐