The topic probably says an n node two fork apple tree, n-1 branch, each branch each has the Apple, 1 is the root, wants to delete several branches, retains the Q branch, asks the most can retain a few apples.
Very simple tree DP, because it is two tree, do not need a tree backpack or anything.
- Dp[u][k] indicates that a subtree with a U node root retains the maximum number of apples the K branch can have.
- Transfer is a number of left dial hand tree, the right sub-tree several transfer.
1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 #defineMAXN 1116 structedge{7 intV,w,next;8}edge[maxn<<1];9 intNE,HEAD[MAXN];Ten voidAddedge (intUintVintW) { OneEdge[ne].v=v; Edge[ne].w=w; edge[ne].next=Head[u]; Ahead[u]=ne++; - } - intN,Q,D[MAXN][MAXN]; the voiddpintUintFA) { -d[u][0]=0; - intlson=-1, rson=-1, W1,W2; - for(intI=head[u]; i!=-1; I=Edge[i].next) { + intv=edge[i].v; - if(V==FA)Continue; + if(lson==-1) lson=v,w1=EDGE[I].W; A ElseRson=v,w2=EDGE[I].W; at DP (V,U); - } - if(lson==-1)return; - if(rson==-1){ - for(intI=0; i<q; ++i) { - if(d[lson][i]==-1)Continue; ind[u][i+1]=max (d[u][i+1],d[lson][i]+W1); - } to return; + } - for(intI=0; i<=q; ++i) { the if(d[lson][i]==-1)Continue; * for(intj=0; j<=q-i; ++j) { $ if(d[rson][j]==-1)Continue;Panax Notoginseng if(i+j+2<=Q) d[u][i+j+2]=max (d[u][i+j+2],d[lson][i]+d[rson][j]+w1+W2); - if(i==0&& j+1<=Q) d[u][j+1]=max (d[u][j+1],d[rson][j]+W2); the if(j==0&& i+1<=Q) d[u][i+1]=max (d[u][i+1],d[lson][i]+W1); + } A } the } + intMain () { - inta,b,c; $ while(~SCANF ("%d%d",&n,&q)) { $Ne=0; -memset (head,-1,sizeof(head)); - for(intI=1; i<n; ++i) { thescanf"%d%d%d",&a,&b,&c); - Addedge (a,b,c);Wuyi Addedge (b,a,c); the } -memset (d,-1,sizeof(d)); Wudp1,1); -printf"%d\n", d[1][q]); About } $ return 0; -}
URAL1018 Binary Apple Tree (DP)