http://poj.org/problem?id=2184
http://blog.csdn.net/liuqiyao_01/article/details/8753686
For a negative volume problem, you can first define a "0 point" shift, set Dp[shift] to 0, and the others to-inf.
The negative volume is then updated from 0 toward Maxn+cost, and the positive volume is updated from MAXN to shift.
Finally, the maximum value is found from shift to MAXN, and the value below shift is not traversed to
#include <iostream>#include<string>#include<cstring>#include<cstdlib>#include<cstdio>#include<cmath>#include<algorithm>#include<stack>using namespacestd;#defineMEM (A, B) memset (A,b,sizeof (a))#definePF printf#defineSF scanf#defineDebug printf ("!\n")#defineINF (0x3f3f3f3f)#defineMAX (A, b) a>b?a:b#defineBlank pf ("\ n")#defineLL Long Long#defineEP 1e-6Const intShift =10000;Const intMAXN =210000;Const intMAXM = the;intDP[MAXN];intCI[MAXM];//capacityintWI[MAXM];//valueintn,v,i,j,v,t,sum;DoubleG;voidZeroonepack (intCostintweight) { if(cost>=0) { for(v = maxn-1; v>=cost;v--) {Dp[v]=max (dp[v],dp[v-cost]+weight); } } Else { for(v =0; v<maxn+cost;v++) {Dp[v]=max (dp[v],dp[v-cost]+weight); } }}intMain () { while(SF ("%d", &n)! =EOF) {MEM (DP,-INF); MEM (WI,0); for(i =0; i<n;i++) {SF ("%d",&Ci[i]); SF ("%d",&Wi[i]); } Dp[shift]=0; for(i =0; i<n;i++) {zeroonepack (ci[i],wi[i]); } intAns =-INF; for(i = shift;i<maxn;i++) { if(dp[i]>=0&& (I-shift+dp[i]) >ans) ans= i-shift+Dp[i]; } PF ("%d\n", ans); } return 0;}/*5-5 78-66-32 1-8-5*/
POJ 2184 (01 Backpack) (negative volume)