ural_1018 Binary Apple tree-shaped dp+ backpack

Source: Internet
Author: User

This topic is given a tree, and the number of apples per branch of the tree, which requires a maximum of how many apples to retain in the case of a K-branch.

I think it's a tree DP, and then come up with a dp[i][j] to show that the I-node retains the maximum number of J-branches, but in the tree process, it's a little difficult to express the transfer

Later saw the big God's practice just know can actually use a backpack to simulate the fate of the branch, in fact, is really a backpack ah, each sub-branch is equivalent to the item, he occupies a number of branches, how much revenue, is to use the backpack, so with the tree-shaped dp+ backpack can be done

#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#defineN 210using namespacestd;intU[n],v[n],e[n],nt[n],ft[n];intDp[n][n];intCNT;voidAddintAintBintval) {u[cnt]=A; V[CNT]=b; E[CNT]=Val; NT[CNT]=Ft[a]; Ft[a]=cnt++;}intn,k;intSum[n];voidDfsintXintf) {Sum[x]=1;  for(inti=ft[x];i>=0; i=Nt[i]) {        intnx=V[i]; if(nx==f)Continue;        DFS (NX,X); SUM[X]+=Sum[nx];  for(intj=sum[x];j>=1; j--){             for(intw=1; W<=sum[nx] && w<j;w++) {Dp[x][j]=max (dp[x][j],dp[x][j-w]+dp[nx][w]+E[i]); }        }    }}intMain () { while(SCANF ("%d%d", &n,&k)! =EOF) {CNT=0; intA,b,c; memset (FT,-1,sizeofft);  for(intI=1; i<n;i++) {scanf ("%d%d%d",&a,&b,&c);            Add (A,B,C);        Add (B,A,C); } memset (DP,0,sizeofDP); DFS (1,-1); printf ("%d\n", dp[1][k+1]); }    return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.