Main topic:
Each node of a tree has several apples. Ask at the root node, the maximum number of apples can be taken if the walk is not greater than the K-step.
Problem Solving Ideas:
The tree DP, for each subtree root node src, has dp[src][i][0], which indicates how many apples can be obtained from SRC walk I step back to SRC. Dp[src][i][1] represents the maximum number of apples that can be obtained from SRC walk I step without returning to SRC.
There are three ways to transfer the status:
1, with I-j-2 step to the other sub-tree back to the root node and then use J step to go to a subtree and then back to the root node.
2, with i-j-2 walk other subtree back to the root node and then walk with a J step a subtree did not return to the root node.
3, with a J step to go to a subtree and then back to the root node in the walk with i-j-1 other subtrees do not go back to the root node.
Note the initialization of the state.
Here's the code:
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include < math.h> #include <stdlib.h> #include <vector> #include <string> #include <map> #include < Queue>using namespace Std;int min (int a,int b) {if (a>b) a=b; return A;} int max (int a,int b) {if (a<b) a=b; return A;} struct node1{int to,next;} Edge[105*2];int head[105],cnt,n,k,applenum[105],u,v,dp[105][205][2];bool vis[105];void addedge (int u,int v) {edge[ Cnt].to=v; Edge[cnt].next=head[u]; head[u]=cnt++; Edge[cnt].to=u; EDGE[CNT].NEXT=HEAD[V]; head[v]=cnt++;} BOOL Chack (int src) {int t=head[src]; while (T!=-1) {if (!vis[edge[t].to]) return true; T=edge[t].next; } return false;} void dfs (int src) {if (vis[src]) return; else vis[src]=true; if (Chack (src)) {int T=HEAD[SRC]; while (T!=-1) {if (vis[edge[t].to]) {t=edge[t].next; Continue } dfs (edge[t].to); for (int i=k;i>0;i--) {for (int j=0;i-j>=0;j++) {if (i-j- 2>=0) {Dp[src][i][0]=max (dp[src][i][0],dp[src][i-j-2][0]+dp[edge[t].to][j][0 ]); Dp[src][i][1]=max (Dp[src][i][1],dp[src][i-j-2][1]+dp[edge[t].to][j][0]); } if (i-j-1>=0) {Dp[src][i][1]=max (dp[src][i][1],dp[src][i -J-1][0]+DP[EDGE[T].TO][J][1]); }}} T=edge[t].next; }}}int Main () {while (scanf ("%d%d", &n,&k)!=eof) {cnt=0; memset (vis,false,sizeof (VIS)); Memset (Dp,0,sizeof (DP)); for (int i=1;i<=n;i++) {head[i]=-1; scanf ("%d", &applenum[i]); } for (int i=1;i<=n;i++) {for (int j=0;j<=k;j++) {Dp[i][j][0]=applenum[i]; Dp[i][j][1]=applenum[i]; }} for (int i=2;i<=n;i++) {scanf ("%d%d", &u,&v); Addedge (U,V); } dfs (1); printf ("%d\n", Max (dp[1][k][0],dp[1][k][1])); } return 0;}