Title Link: https://vjudge.net/problem/POJ-3624
Test instructions: There are n items, each with a different weight of WI and value Di,bessie can only take away items with a weight of not more than M, if the total value is the largest, and output the total value.
Start with the normal DP and then display the hyper memory, and press the code below also hyper memory (DP array too Large) but this method can learn
#include <iostream>#include<cstring>using namespacestd;intn,m;//int w[3403],d[12881];intv,w;intdp[3403][12881];intMain () {Ios::sync_with_stdio (false); CIN>>n>>m; Memset (DP,0,sizeof(DP)); for(intI=1; i<=n;i++) {cin>>V>>w;//can not save the v,w . for(intj=0; j<=m;j++) {Dp[i][j]= (i==1?0:d p[i-1][j]); if(j>=V) {Dp[i][j]=max (dp[i-1][j],dp[i-1][j-v]+v); } }} cout<<dp[n][m]<<Endl; return 0;}
AC Code: (Note the size of the array f)
#include <iostream>#include<cstring>using namespacestd;intn,m;intv,w;intf[12880+5];intMain () {Ios::sync_with_stdio (false); CIN>>n>>m; Memset (F,0,sizeof(f)); for(intI=1; i<=n;i++) {cin>>V>>W; for(intj=m;j>=0; j--) { if(j>=v) F[j]=max (f[j],f[j-v]+W);//Consider not putting the previous deposit in order to reach the maximum} cout<<f[m]<<Endl; return 0;}
The f array is stored from top to bottom, left to right, F[j] is f (i-1,j), f[j-w] is F (i-1,j-w) (Note that J is enumerated in reverse order)
So f[j]=max{f[j],f[j-v]+w}
Actually overwrite the value before F[j] with max{f[j],f[j-v]+w}
Using a scrolling array
Scrolling arrays use 2x1000 space to solve problems, and scroll to get the same effect as 1000x1000
Scrolling array related see: 52180788
poj3624 Charm Bracelet (0-1 backpack scrolling array)