Also a good question, with a limited 01 backpack, sorted first, then backpack
This problem is related to Q, so it is not directly on the 01 backpack. Because if an item is 5 9, an item is 5 6, on the first backpack when only dp[9],dp[10],..., dp[m], and then the second to carry the backpack, if it is normal, should borrow the front dp[8],dp[7], but now these values are 0, This can result in an error. So you have to think that only the value of the back to be used before can be obtained, then will not be wrong. Set A:P1,Q1 b:p2,q2, if first a after B, then at least p1+q2 capacity, if the first B after a, at least p2+q1 capacity, then P1+Q2 > p2+q1, after deformation is Q1-P1 < Q2-P2.
1#include <stdio.h>2#include <string.h>3#include <algorithm>4#include <iostream>5 using namespacestd;6 Const intmaxn=550;7 structNode8 {9 intp,q,v;Ten }NODE[MAXN]; One intdp[5500]; A BOOLCMP (Node A,node B)//Sort by q-p from small to large - { - returnA.Q-A.P < b.q-B.P; the } - intMain () - { - intn,m; + while(SCANF ("%d%d", &n,&m)! =EOF) - { + for(intI=0; i<n;i++) Ascanf"%d%d%d",&node[i].p,&node[i].q,&node[i].v); atSort (node,node+n,cmp); -Memset (DP,0,sizeof(DP)); - for(intI=0; i<n;i++) - for(intj=m;j>=node[i].q;j--) -Dp[j]=max (dp[j],dp[j-node[i].p]+node[i].v); -printf"%d\n", Dp[m]); in } - return 0; to}
Hdu 3466 Sort 01 Backpack