hdu 1561

有依赖的背包,用树形dp解

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 205
using namespace std;
int n,m;
int f[maxn][maxn];

struct node
{
    int pre;
    int cnt_son;
    int son[maxn];
    int value;
} no[maxn];

void dfs(int x)
{
    f[x][1]=no[x].value;
    int v;
    for(int i=0; i<no[x].cnt_son; i++)
    {
        v=no[x].son[i];
        dfs(v);
        for(int j=m+1; j>1; j--)//从大往小更新,结果不会覆盖;
        {
            for(int k=1; k<j; k++)//不能更新f[x][1]点
            {
                f[x][j]=max(f[x][j],f[x][j-k]+f[v][k]);
            }
        }
    }
}

int main()
{
    int fa;
    while(scanf("%d%d",&n,&m)&&(n+m))
    {
        memset(f,0,sizeof f);
        for(int i=0; i<=n; i++)
        {
            no[i].cnt_son=0;
            no[i].pre=0;
            no[i].value=0;
        }
        for(int i=1; i<=n; i++)
        {
            scanf("%d%d",&no[i].pre,&no[i].value);
            fa=no[i].pre;
            no[fa].son[no[fa].cnt_son]=i;
            no[fa].cnt_son++;
        }
        dfs(0);
        printf("%d\n",f[0][m+1]);//增加了一个节点,所以用m+1
    }
    return 0;
}
/*
11 5
0 1
1 2
1 1
2 1
2 2
3 1
6 9
0 2
8 2
8 2
9 1
*/
View Code

 

posted @ 2014-04-08 14:13  Yours1103  阅读(109)  评论(0编辑  收藏  举报