hdu 1561 The more, The Better 树形dp水题

Description

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

 

比较简单的树形dp,定义dp[i][j]:在以i为根的子树中,且有j次机会能取得的最大宝物值。

水题,不解释。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
const int MAXM = 205;
const int MAXN = 205;

///树形dp部分

struct Edge
{
    int to,next;
} edge[MAXM];
int head[MAXN],tot;
void addedge(int u,int v)
{
    edge[tot].to = v;
    edge[tot].next = head[u];
    head[u] = tot++;
}
void init()
{
    tot = 0;
    memset(head,-1,sizeof(head));
}


int n,m;
int dp[MAXN][MAXN];
int p[MAXN]={0};
void dfs(int u) {
    dp[u][1] = p[u];
    if(head[u]==-1) for(int i=2;i<=m;i++) dp[u][i] = p[u];
    for(int e=head[u];e!=-1;e=edge[e].next) {
        int v = edge[e].to;
        dfs(v);
        for(int i=m;i>=2;i--) {
            for(int j=1;j<i;j++) {
                dp[u][i] = max(dp[u][i],dp[u][i-j]+dp[v][j]);
            }
        }
    }
}


int main()
{
    int a;
    while(scanf("%d%d",&n,&m)==2&&n&&m)
    {
        m++;
        init();
        memset(dp,0,sizeof(dp));
        for(int i=1; i<=n; i++)
        {
            scanf("%d%d",&a,&p[i]);
            addedge(a,i);
        }
        dfs(0);
        printf("%d\n",dp[0][m]);
    }
    return 0;
}
posted @ 2016-04-06 18:55  ZhMZ  阅读(179)  评论(0编辑  收藏  举报