hdu1011 - 树形dp

Posted redips

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu1011 - 树形dp相关的知识,希望对你有一定的参考价值。

题目链接

 

#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>

#define MAX(a,b) ((a)>=(b)?(a):(b))
#define MIN(a,b) ((a)<=(b)?(a):(b))
#define long long LL
#define OO 0x0fffffff
using namespace std;

const int N = 111;
int heads[N];
struct Edge{
    int to;
    int next;
};
Edge edgs[N*2];
int eid = 0;
void addEdge(int a,int b){
    edgs[eid].to = b;
    edgs[eid].next = heads[a];
    heads[a] = eid++;

    edgs[eid].to = a;
    edgs[eid].next = heads[b];
    heads[b] = eid++;
}
int n,m;
int dp[N][N];
int cost[N],value[N],visited[N];
void traverse(int id){
    visited[id] = 1;
    for(int i=cost[id];i<=m;i++) dp[id][i] = value[id];
    for(int cur=heads[id];cur!=-1;cur=edgs[cur].next){
        int to = edgs[cur].to;
        if(visited[to]) continue;
        traverse(to);

        for(int i=m;i>=cost[id];i--){
             for(int j=1;j+i<=m;j++){
                 dp[id][i+j]=MAX(dp[id][i+j],dp[id][i]+dp[to][j]);
             }
        }
    }
}

int main(){
    int a,b;
    while(scanf("%d%d",&n,&m),m>=0&&n>=0){
        eid = 0;
        memset(heads,-1,sizeof(heads));
        for(int i=1;i<=n;i++){
            scanf("%d%d",&a,value+i);
            cost[i] = (a+19)/20;
        }
        for(int i=1;i<n;i++){
            scanf("%d%d",&a,&b);
            addEdge(a,b);
        }
        memset(visited,0,sizeof(visited));
        memset(dp,0,sizeof(dp));

        if(m==0) {
            puts("0");
            continue;
        }

        traverse(1);
        printf("%d\n",dp[1][m]);
    }
    return 0;
}

 

以上是关于hdu1011 - 树形dp的主要内容,如果未能解决你的问题,请参考以下文章

hdu 1011 树形dp

hdu1011 - 树形dp

hdu_1011(Starship Troopers) 树形dp

HDU 1011 Starship Troopers(树形DP)

hdu1011(树形背包)(提供一个特殊样例)

hdu1011Starship Troopers(树形背包)