POJ-2486 Apple Tree (dp)

Source: Internet
Author: User
<span id="Label3"></p><p><p>The main topic: a point with the right to have a root tree, the root node is 1. From the root node, take the k-step, to collect the maximum weight and.</p></p><p><p>Problem Analysis: There are three possible scenarios for starting from a point to one of its subtrees trees:</p></p><p><p>1, stay in that subtrees tree;</p></p><p><p>2, return to this point;</p></p><p><p>3, through this point toward the other branches;</p></p><p><p>The definition state DP (U,K,0/1) indicates that the U node walks on a subtree of the root and does not return/back to the maximum weight of U and. The state transition Equation is:</p></p><p><p>DP (u,k,0) =max (DP (son,j-2,1) +DP (u,k-j,0), dp (u,k-j,1) +DP (son,j-1,0))</p></p><p><p>DP (u,k,1) =max (DP (son,j-2,1) +DP (u,j-k,1))</p></p><p><p></p></p><p><p>The code is as Follows:</p></p><pre class="brush:cpp;gutter:true;"><pre class="brush:cpp;gutter:true;"># include<iostream># include<cstdio># include<vector># include<cstring># include<algorithm>using namespace Std;const int n=105;int n,m;int w[N];int dp[N][N< <1][2];vector<int>e[n];void init () {memset (dp,0,sizeof (dp)); for (int i=1;i<=n;++i) {e[i].clear (); scanf ( "%d", w+i); for (int j=0;j<=m;++j) dp[i][j][0]=dp[i][j][1]=w[i];} int a,b;for (int i=1;i<n;++i) {scanf ("%d%d", &a,&b); e[a].push_back (b); e[b].push_back (a);}} void Dfs (int u,int fa) {for (int i=0;i<e[u].size (); ++i) {int v=e[u][i];if (v==fa) continue;dfs (v,u), for (int j=m;j>= 1;--j) {for (int k=1;k<=j;++k) {dp[u][j][0]=max (dp[u][j][0],dp[v][k-1][0]+dp[u][j-k][1]), if (k>=2) {dp[u][j][0 ]=max (DP[U][J][0],DP[V][K-2][1]+DP[U][J-K][0]);DP [u][j][1]=max (dp[u][j][1],dp[v][k-2][1]+dp[u][j-k][1]);}}}} void solve () {dfs (1,-1);p rintf ("%d\n", Max (dp[1][m][0],dp[1][m][1]));} int main () {while (~scanf ("%d%d", &n,&m)) {init (); solve ();} return 0;} </pre></pre><p><p>  </p></p><p><p>POJ-2486 Apple Tree (dp)</p></p></span>

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.