#include <iostream> #include <cstring> #include <deque>using namespace std; #define SIZE 230#define Back 1#define away 0int dp[size][size][2];bool visits[size];int vals[size];d eque< int > Tree[size];int num, steps;v OID dfs (int u) {Visits[u] = true; const int len = Tree[u].size (); for (int i = 0; I <= steps; ++i) dp[u][i][back] = Dp[u][i][away] = Vals[u]; for (int i = 0; i < len; ++i) {int son = tree[u][i]; if (Visits[son]) continue; DFS (son); for (int s = steps; s >= 0,--s) {for (int ss = 0; SS <= S; ++ss) {/* Starting from U, go back to u, need to walk two more steps u->son,son->u, assign to son Tree SS step, other subtree s-ss step, all return. */Dp[u][s + 2][back] = max (Dp[u][s + 2][back], Dp[u][s-ss][bac K] + dp[son][ss][back]); /* Do not back u (go to other subtrees of U), return at son. */ Dp[u][s + 2][away] = max (Dp[u][s + 2][away], Dp[u][s-ss][away] + Dp[son][ss][back]); /* Go through the other subtrees of U, go back to u, traverse son subtree, and go one more step in the current subtree. */Dp[u][s + 1][away] = max (Dp[u][s + 1][away], Dp[u][s-ss][bac K] + dp[son][ss][away]); }}}}int Main () {int u, v; while (CIN >> num >> steps) {memset (DP, 0, sizeof (DP)); Memset (visits, false, sizeof (visits)); for (int i = 1; I <= num; ++i) tree[i].clear (); for (int i = 1; I <= num; ++i) cin >> Vals[i]; for (int i = 1; I <= num-1; ++i) {cin >> u >> v; Tree[u].push_back (v); Tree[v].push_back (U); } dfs (1); cout << Max (Dp[1][steps][back], Dp[1][steps][away]) << Endl; } return 0;}
POJ 2486 Apple Tree (DP)