/** * @file POJ2486.cpp * @author your name ([email protected]) * @brief * @version 0.1 * @date 2024-08-21 * * @copyright Copyright (c) 2024 This is a common Tree DP problem. The problem say we can move k times at more. so , We can set the DP[i][j][0/1] to calc : when we is on node i then move j times the maximum of Apple that we can get. 0 is we are return to node i , 1 is we are not return to node i. */
structEdge { int to, nt; Edge() {} Edge(int to, int nt) : to(to), nt(nt) {} }e[N << 1]; int hd[N], cnte; voidAddEdge(int u, int v){ e[++cnte] = Edge(v, hd[u]); hd[u] = cnte; }
int n, K; int a[N];
int dp[N][210][2];
inlinevoidInput(){ read(n, K); for(int i = 1; i <= n; i++) { read(a[i]); } int u, v; for(int i = 1; i < n; i++) { read(u, v); AddEdge(u, v); AddEdge(v, u); } }
voidDfs(int u, int fa){ for(int i = 0; i <= K; i++) { dp[u][i][0] = dp[u][i][1] = a[u]; } for(int i = hd[u]; i ; i = e[i].nt) { int v = e[i].to; if(v == fa) continue; Dfs(v, u); for(int j = K; j >= 0; j--) { for(int k = 1; k <= j; k++) { dp[u][j][0] = max(dp[u][j][0], dp[u][j - k][1] + dp[v][k - 1][0]); if(k < 2) continue; dp[u][j][0] = max(dp[u][j][0], dp[u][j - k][0] + dp[v][k - 2][1]); dp[u][j][1] = max(dp[u][j][1], dp[u][j - k][1] + dp[v][k - 2][1]); } } } }