Question:
Give a tree, find the maximum value of the treasure that can be obtained from the start point, take m length, and return to the start point.
Train of Thought Analysis:
One DFS operation can obtain the maximum distance from the subtree to the root node.
Now the problem is that he can go to another subtree after walking through one subtree.
Therefore, when tracing to the root, We need to calculate the maximum complementary distance of other Subtrees.
DP [I] [J] indicates that I is the root node. Step J in the subtree of I and return to the maximum value I can get.
The transfer equation is
DP [x] [I + 2 * Len] = max (DP [x] [I + 2 * Len], DP [v] [J] + dp [x] [I-j]);
The root of the subtree whose V is X and the distance between Len and X-V
# Include <cstdio> # include <iostream> # include <cstring> # define maxn 105 using namespace STD; int DP [maxn] [maxn <1]; int Val [maxn]; int n, m, K; int tot; int head [maxn]; int next [maxn <1]; int to [maxn <1]; int cost [maxn <1]; void Init () {tot = 0; memset (Head, 0, sizeof head);} void addedge (int u, int V, int W) {tot ++; next [tot] = head [u]; To [tot] = V; cost [tot] = W; head [u] = tot ;} bool vis [maxn]; void DFS (int X) {for (INT I = 0; I <= m; I ++) DP [x] [I] = 0; For (INT P = head [x]; p; P = next [p]) {int v = to [p]; If (vis [v]) continue; int Len = cost [p]; vis [v] = true; DFS (V); For (INT I = m; I> = 0; I --) {if (I + 2 * Len> m) continue; for (Int J = 0; j <I; j ++) DP [x] [I + 2 * Len] = max (DP [x] [I + 2 * Len], DP [v] [J] + dp [x] [I-j]) ;}for (INT I = Len * 2; I <= m; I ++) DP [x] [I] = max (DP [x] [I], DP [v] [I-len * 2]);} For (INT I = 0; I <= m; I ++) DP [x] [I] + = Val [X];} int main () {While (scanf (" % D ", & N )! = EOF) {Init (); For (INT I = 1; I <= N; I ++) scanf ("% d", & Val [I]); for (INT I = 2; I <= N; I ++) {int L, R, W; scanf ("% d", & L, & R, & W); addedge (L, R, W); addedge (R, L, W);} scanf ("% d", & K, & M); memset (VIS, false, sizeof vis); vis [k] = true; DFS (k); int ans = 0; For (INT I = 0; I <= m; I ++) {ans = max (ANS, DP [k] [I]);} printf ("% d \ n", ANS );} return 0 ;}