The more, The Better HDU - 1561 (转化为树行01背包)

ACboy很喜欢玩一种战略游戏,在一个地图上,有N座城堡,每座城堡都有一定的宝物,在每次游戏中ACboy允许攻克M个城堡并获得里面的宝物。但由于地理位置原因,有些城堡不能直接攻克,要攻克这些城堡必须先攻克其他某一个特定的城堡。你能帮ACboy算出要获得尽量多的宝物应该攻克哪M个城堡吗? 

Input

每个测试实例首先包括2个整数,N,M.(1 <= M <= N <= 200);在接下来的N行里,每行包括2个整数,a,b. 在第 i 行,a 代表要攻克第 i 个城堡必须先攻克第 a 个城堡,如果 a = 0 则代表可以直接攻克第 i 个城堡。b 代表第 i 个城堡的宝物数量, b >= 0。当N = 0, M = 0输入结束。

Output

对于每个测试实例,输出一个整数,代表ACboy攻克M个城堡所获得的最多宝物的数量。

Sample Input

3 2
0 1
0 2
0 3
7 4
2 2
0 1
0 4
2 1
7 1
7 6
2 2
0 0

Sample Output

5
13

思路:等价于要想得到财宝就必须去花费1的容量,多加一个0节点(不花费容量),在将有依赖关系的建立边,跑一遍树形背包就好了。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
#define inf 0x3f3f3f3f
int n,m;
int num;
int head[maxn];
int dp[300][300];
struct Edge
{
    int u,v,next,w;
}edge[maxn<<1];
int h[maxn];
int w[maxn];
void addEdge(int u,int v,int w)
{
    edge[num].u=u;
    edge[num].v=v;
    edge[num].w=w;
    edge[num].next=head[u];
    head[u]=num++;
}
void init()
{
    num=0;
    memset(head,-1,sizeof(head));
    memset(dp,0,sizeof(dp));
}
void dfs(int u,int pre)
{
    for(int i=w[u];i<=m;i++)
    {
        dp[u][i]=h[u];
    }
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int v=edge[i].v;
        if(v==pre) continue;
        dfs(v,u);
        for(int j=m;j>=w[u];j--)
        {
            for(int k=1;k<=j-w[u];k++)
            {
                dp[u][j]=max(dp[u][j],dp[v][k]+dp[u][j-k]);
            }
        }
    }
}
int main(int argc, char const *argv[])
{
   #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    while(scanf("%d%d",&n,&m)!=EOF&&n+m)
    {
        init();
        w[0]=0,h[0]=0;
        for(int i=1;i<=n;i++)
        {
            int a,x;
            scanf("%d%d",&a,&x);
            addEdge(a,i,0);
            h[i]=x;
            w[i]=1;
            addEdge(i,a,0);
        }
        dfs(0,0);
        cout<<dp[0][m]<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/81450362
今日推荐