【树形DP】 HDU 1561 The more, The Better

经典树形DP


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <cmath>
using namespace std;
#include <queue>
#include <stack>
#include <vector>
#include <deque>
#include <set>
#include <map>
#include <time.h>;
#define cler(arr, val)    memset(arr, val, sizeof(arr))
#define FOR(i,a,b)  for(int i=a;i<=b;i++)
#define IN   freopen ("in.txt" , "r" , stdin);
#define OUT  freopen ("out.txt" , "w" , stdout);
typedef long long  LL;
const int MAXN = 201;
const int MAXM = 201;
const int INF = 0x3f3f3f3f;
const int mod = 1000000007;
struct node
{
    int v,next;
} edge[MAXM];
int n,m;
int head[MAXM],tol,val[MAXN],dp[MAXN][MAXN];
void init()
{
    cler(val,0);
    cler(head,-1);
    tol=0;
}
void addedge(int u,int v)
{
    edge[tol].v=v,edge[tol].next=head[u];
    head[u]=tol++;
}
void dfs(int u)
{
    for(int i=0; i<=m; i++)
        dp[u][i]=-INF;
    dp[u][1]=val[u];
    for(int i=head[u]; ~i; i=edge[i].next)
    {
        int v=edge[i].v;
        dfs(v);
        for(int j=m; j>=0; j--)
            for( int k=0; k<=j; k++)
                dp[u][j]=max(dp[u][j],dp[v][k]+dp[u][j-k]);
    }
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif
    while(~scanf("%d%d",&n,&m),n+m)
    {
        init();
        for(int i=1; i<=n; i++)
        {
            int a;
            scanf("%d %d",&a ,&val[i] );
            addedge(a,i);
        }
        m++;
        dfs(0);
        printf("%d\n",dp[0][m]);
    }
}


posted @ 2014-10-04 21:48  kewowlo  阅读(112)  评论(0编辑  收藏  举报