HDOJ 1561-tree DP, generalized backpack

Source: Internet
Author: User

Just read the question... I think this is not a tree... there may be loops... think twice .. this is really a tree (forest )... this is because each castle needs to break down at most one castle in advance .. for a castle. the castle that needs to be broken in advance as its father's diagram ....

Dp [k] [I] represents the maximum benefit that a k-followed subtree can achieve when it breaks through the I castle... generalized knapsack problem...

 


Program:

 

#include<iostream>#include<stack>#include<queue>#include<stdio.h>#include<algorithm>#include<string.h>#include<cmath>#define ll long long#define oo 1000000007#define MAXN 205using namespace std;vector<int> Tree[MAXN];int n,m,v[MAXN],ans[MAXN],dp[MAXN][MAXN];bool root[MAXN];void dfs(int x,int t){      int i,j,k,num;      if (t>m) return;      dp[x][1]=v[x];       num=Tree[x].size();      for (i=0;i<num;i++)      {            dfs(Tree[x][i],t+1);             for (j=m;j>=1;j--)               for (k=1;k<=m-j;k++)                  dp[x][j+k]=max(dp[x][j+k],dp[x][j]+dp[Tree[x][i]][k]);      }      return;}int main(){      int i,j,k;       while (~scanf("%d%d",&n,&m) && n && m)      {             for (i=1;i<=n;i++) Tree[i].clear();             memset(root,true,sizeof(root));             for (i=1;i<=n;i++)             {                   int x,c;                   scanf("%d%d",&x,&c);                   Tree[x].push_back(i);                   v[i]=c;                   if (x) root[i]=false;             }             memset(dp,0,sizeof(dp));             memset(ans,0,sizeof(ans));             for (i=1;i<=n;i++)               if (root[i])               {                      dfs(i,1);                      for (j=m;j>=0;j--)                         for (k=0;k<=m-j;k++)                             ans[j+k]=max(ans[j+k],ans[j]+dp[i][k]);               }            for (i=m;i>=0;i--)              if (ans[i]) break;            printf("%d\n",ans[i]);      }      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.