hdu1561 (tree-shaped dp+01 backpack) The more, the Better

Source: Internet
Author: User

This topic just began to think for a while, because it is a tree-like DP topic, so did not see it is 01 backpack (the focus is to reverse), reverse this point has not been thought out why, because the treasure only one, and 01 backpack is the same meaning (actually I now I do not want to understand that since it is already two-dimensional, And why to reverse it), the state transfer equation is Dp[u][j]=max (dp[u][j],dp[u][j-k]+dp[v][k]), because I was in the process of building 0 as the heel, the equivalent of more than a fortress, do in order to be dp[0][m+1])
The code is as follows:

#include <iostream> #include <string.h> #include <stdio.h> using namespace std;
int n,m,edge,a;
const int maxn=205;
int DP[MAXN][MAXN];
int HEAD[MAXN],VAL[MAXN];
    struct node {int to;
int next;
}TREE[MAXN];
    void Init () {memset (dp,0,sizeof (DP));
    memset (head,-1,sizeof (head));
edge=0;
    } void Addedge (int u,int v) {tree[edge].to=v;
    Tree[edge].next=head[u];
head[u]=edge++;
    } void Dfs (int u) {dp[u][1]=val[u];
        for (int i=head[u];i!=-1;i=tree[i].next) {int v=tree[i].to;
        DFS (v);
    for (int. j=n;j>=1;j--) for (int k=1;k<j;k++) Dp[u][j]=max (Dp[u][j],dp[u][j-k]+dp[v][k]);
        }} int main () {while (scanf ("%d%d", &n,&m)!=eof) {if (n==0&&m==0) break;
        Init ();
            for (int i=1;i<=n;i++) {scanf ("%d%d", &a,&val[i]);
        Addedge (A,i);
        } dfs (0);
    printf ("%d\n", dp[0][m+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.