5 10 1 2 2 2 3 2 2 5 3 3 4 3 1 2 3 4 5
11
#include <iostream> #include <cstdio> #include <vector> #include <cstring> #include <algorithm> using namespace std; const int maxn = 110; const int maxt = 510; int dp[maxn][maxt] , A[maxn] , vis[maxn] , ans[maxt]; int way[maxn]; int N , T , cnt , sumT , route; struct edge{ int u , v , t , next; edge(int a = 0 , int b = 0, int c = 0 , int d = 0){ u = a , v = b , t = c , next = d; } }e[4*maxn]; int head[maxn]; void add(int u , int v , int t){ e[cnt] = edge(u , v , t , head[u]); head[u] = cnt++; } void initial(){ for(int i = 0; i < maxn; i++){ head[i] = -1; A[i] = 0; vis[i] = 0; for(int j = 0; j < maxt; j++) dp[i][j] = 0; } for(int i = 0; i < maxt; i++) ans[i] = 0; cnt = 0; sumT = 0; route = 0; } void readcase(){ int u , v , t; for(int i = 0; i < N-1; i++){ scanf("%d%d%d" , &u , &v , &t); add(u , v , t); add(v , u , t); } for(int i = 1; i <= N; i++){ scanf("%d" , &A[i]); } } void DP(int k , int f){ dp[k][0] = A[k]; for(int i = head[k]; i != -1; i = e[i].next){ int son = e[i].v; if(son != f){ DP(son , k); if(vis[son]) continue; for(int t = T; t >= 0; t--){ if(dp[k][t] == 0 && t != 0) continue; for(int j = T; j >= 0; j--){ if(dp[son][j] != 0 && t+j+2*e[i].t <= T && dp[k][t+j+2*e[i].t] < dp[k][t]+dp[son][j]) dp[k][t+j+2*e[i].t] = dp[k][t]+dp[son][j]; } } } } } bool dfs(int k , int index , int f){ way[index] = k; route = index; if(k == N) return true; for(int i = head[k]; i != -1; i = e[i].next){ int son = e[i].v; if(f != son){ sumT += e[i].t; if(dfs(son , index+1 , k)) return true; sumT -= e[i].t; } } return false; } void computing(){ dfs(1 , 0 , 1); for(int i = 0; i <= route; i++) vis[way[i]] = 1; DP(1 , 1); if(sumT > T){ printf("Human beings die in pursuit of wealth, and birds die in pursuit of food!\n"); return; } T -= sumT; for(int i = 0; i <= route; i++){ for(int t = T; t >= 0; t--){ if(ans[t] == 0 && t != 0) continue; for(int j = T; j >= 0; j--){ if(t+j <= T && ans[t+j] < ans[t]+dp[way[i]][j]) ans[t+j] = ans[t]+dp[way[i]][j]; } } } int Max = 0; for(int i = 0; i <= T; i++) if(Max < ans[i]) Max = ans[i]; printf("%d\n" , Max); } int main(){ while(~scanf("%d%d" , &N , &T)){ initial(); readcase(); computing(); } return 0; }
hdu 4276 The Ghost Blows Light(DP-树形DP)
原文地址:http://blog.csdn.net/u011836218/article/details/38929975