【HDU】The Ghost Blows Light(树状DP)

树上的背包DP,还是思路不够。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 111;
const int tmaxn = 550;
int Map[maxn][maxn];
int  dp[maxn][tmaxn];
int pri[maxn];
int vis[maxn];
int  n,T,ans;
void init(){
    memset(dp,0,sizeof(dp));
    memset(Map,-1,sizeof(Map));
    memset(vis,0,sizeof(vis));
    ans = 0;
}
void dfs_dp(int cur){
    vis[cur] = 1;
    for(int i = 1; i <= n ; i++)if(Map[cur][i] != -1 && !vis[i]){
        dfs_dp(i);
        for(int j = T ; j >= 0 ; j--)
            for(int k = 0 ; k + 2 * Map[cur][i] <= j ; k++)
                dp[cur][j] = max(dp[cur][j],dp[cur][j - 2 * Map[cur][i] - k] + dp[i][k] + pri[i]);
    }
    return ;
}
bool dfs_path(int cur,int sum_path){
    vis[cur] = 1;
    if(cur == n){
        ans += pri[n];
        pri[n] = 0;
        T -= sum_path;
        return true;
    }
    for(int i = 1 ; i <= n; i++)
        if(Map[cur][i] != -1 && !vis[i]){
            if(dfs_path(i,sum_path + Map[cur][i])){//如果这条路劲能够到达n点
                Map[cur][i] = Map[i][cur] = 0;     //1 - n的路径的权值赋值为0
                ans += pri[cur];                   //宝藏也全部加到结果上
                pri[cur] = 0;                      //宝藏赋值为0
                return true;
            }
        }
    return false;
}
int main(){
    while(scanf("%d%d",&n,&T) != EOF){
        init();
        for(int i = 0 ; i < n - 1; i++){
            int x ,y ,t;
            scanf("%d%d%d",&x,&y,&t);
            Map[x][y] = Map[y][x] = t;
        }
        for(int i = 1 ; i <= n ; i++)
            scanf("%d",&pri[i]);
        dfs_path(1,0);
        //printf("\n%d %d\n",ans,T);
        if(T < 0)
            printf("Human beings die in pursuit of wealth, and birds die in pursuit of food!\n");
        else{
            memset(vis,0,sizeof(vis));
            dfs_dp(1);
            printf("%d\n",dp[1][T] + ans);
        }
    }
    return 0;
}

你可能感兴趣的:(【HDU】The Ghost Blows Light(树状DP))