Give you a binary tree, each side has a weight, ask you to keep from the root (1) at the beginning of a piece of the Q bar, can get the maximum value is how much
First, the weight on the edge to the point, N points N-1 edge, that is, a virtual edge to the root, the weight value of 0, each u->v on the weight of the V
DP[I][J] indicates that a subtree with the root of I retains the maximum benefit of J points, so defined, when j!=0 indicates that only I is selected, then
Dp[i][j]=max (Dp[son[i][0]][k],dp[son[i][1]][j-k-1]) +val[i],0<=k<j
Dp[i][j]=0,j<=0
In addition, son[i][0] and son[i][1] need to construct the tree beforehand.
It is also important to note that node I may have only 1 children, or no children, is a leaf node, the small trick to deal with such situations is that the beginning will son[i][0] and son[i][1] are initialized to 0, and then the process of memory search, if i=0, directly return 0
Code:
#include <iostream> #include <memory.h> #include <string> #include <cstdio> #include < algorithm> #include <math.h> #include <stack> #include <queue> #include <vector> #include
<map> using namespace std; struct node {int v,w,next;}
G[1005];
int adj[105],dp[105][105],son[105][2],apple[105];
int n,m,e;
void Add (int u,int v,int W) {g[e].v=v; g[e].w=w; g[e].next=adj[u]; adj[u]=e++;} void build (int u,int fa) {int i,v;
for (I=adj[u];i!=-1;i=g[i].next) {v=g[i].v;
if (V==FA) continue;
APPLE[V]=G[I].W;
if (son[u][0]==0) son[u][0]=v;
else son[u][1]=v;
Build (V,u);
}} int dfs (int u,int k) {if (u==0) return 0;
if (dp[u][k]!=-1) return dp[u][k];
int ans=0,i,j=0,v;
for (i=0;i<k;i++) Ans=max (Ans,dfs (son[u][0],i) +dfs (son[u][1],k-i-1) +apple[u]);
Dp[u][k]=ans;
return dp[u][k];
} int main () {int i,j,k,l;
while (scanf ("%d%d", &n,&m)!=eof) {memset (adj,-1,sizeof (adj));
Memset (Dp,-1,sizeof (DP)); MemsET (son,0,sizeof (son));
e=0;
for (l=1;l<n;l++) {scanf ("%d%d%d", &i,&j,&k);
Add (i,j,k);
Add (j,i,k);
} build (1,-1);
apple[1]=0;
DFS (1,M+1);
printf ("%d\n", dp[1][m+1]);
} return 0; }