HDU3466 01 backpack

Source: Internet
Author: User

Generally, two numbers represent the number of items and the amount of money you bring. Each item has three values, p, q, and v, respectively indicating the money you spent buying the item, the lowest cost for buying this item, and the value of the item. Obtain the greatest value.

Obviously, it's a 01 backpack.

The state transition equation is:
For (I = 0; I <n; I ++)

For (j = m; j> = a [I]. q; j --)

Dp [j] = max (dp [j], dp [j-a [I]. p] + a [I]. w ).

 

Dp [j-a [I]. p] It must be calculated first than dp [j]. The minimum j value is a [I]. q, so we need to sort q-p in ascending order.

The Code is as follows:

 1 #include <stdio.h> 2 #include <string.h> 3 #include <iostream> 4 #include <algorithm> 5 using namespace std; 6  7 struct mem{ 8     int p, q, w; 9 }a[550];10 11 bool cmp(mem a,mem b)12 {13     return a.q-a.p<b.q-b.p;14 }15 16 main()17 {18     int n, m, dp[5005], i, j, k;19     while(scanf("%d%d",&n,&m)==2)20     {21         for(i=0;i<n;i++)22     scanf("%d %d %d",&a[i].p,&a[i].q,&a[i].w);23     sort(a,a+n,cmp);24     memset(dp,-1,sizeof(dp));25     for(i=0;i<n;i++)26     {27         for(j=m;j>=a[i].q;j--)28         dp[j]=max(dp[j],dp[j-a[i].p]+a[i].w);29     }30     printf("%d\n",dp[m]+1);31     }32     33 }

 

 

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.