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 }