This is a backpack transfer on a tree. Note to use Dp[i][j][k] to indicate that the first node uses J's journey back to the I node, k=0 represents the return to I point, k=1 that does not return to I point. So it's actually a backpack shift on the tree.
#include <set> #include <map> #include <queue> #include <stack> #include <cmath> #include <string> #include <cctype> #include <cstdio> #include <cstdlib> #include <cstring># Include <iomanip> #include <iostream> #include <algorithm>using namespace std;typedef long LL; const int inf = 0x3fffffff;const int mmax =110;struct node{int en; int next;} E[2*mmax];int p[mmax],w[mmax],num;int dp[mmax][210][2];void init () {memset (p,-1,sizeof p); num=0;} void Add (int st,int en) {e[num].en=en; E[NUM].NEXT=P[ST]; p[st]=num++;} int N,k;bool vis[mmax];void DFS (int u) {vis[u]=1; for (int i=p[u];i+1;i=e[i].next) {int v=e[i].en; if (!vis[v]) {DFS (v); for (int j=k;j>=0;j--) {for (int e=0;e<=k;e++) {if (j-e-2 >=0 && dp[u][j-e-2][0]+1 && dp[v][e][0]+1) { Dp[u][j][0]=max (Dp[u][j][0],dp[u][j-e-2][0]+dp[v][e][0]); } if (j-e-1>=0 && dp[u][j-e-1][0]+1) {if (dp[v][e][ 0]+1) Dp[u][j][1]=max (dp[u][j][1],dp[u][j-e-1][0]+dp[v][e][0]); if (dp[v][e][1]+1) Dp[u][j][1]=max (dp[u][j][1],dp[u][j-e-1][0]+dp[v][e][1]); } if (j-e-2>=0 && dp[u][j-e-2][1]+1 && dp[v][e][0]+1) { Dp[u][j][1]=max (Dp[u][j][1],dp[u][j-e-2][1]+dp[v][e][0]); }}}}}}int main () {while (cin>>n>>k) {init (); memset (dp,-1,sizeof DP); for (int i=1;i<=n;i++) {scanf ("%d", &w[i]); Dp[i][0][0]=dp[i][0][1]=w[i]; } for (int i=1;i<n;i++) {int u,v; scanf"%d%d", &u,&v); Add (U,V); Add (V,u); } memset (vis,0,sizeof vis); DFS (1); int ans=0; for (int i=0;i<=k;i++) {Ans=max (ans,dp[1][i][0]); Ans=max (ans,dp[1][i][1]); } printf ("%d\n", ans); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ 2486 Apple Tree (DP)