码迷,mamicode.com
首页 > 其他好文 > 详细

hdu1011 - 树形dp

时间:2017-05-13 23:23:21      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:cstring   long   next   fine   size   math   show   ble   href   

题目链接

 

#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

标签:cstring   long   next   fine   size   math   show   ble   href   

原文地址:http://www.cnblogs.com/redips-l/p/6850680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!