Backpack problems, 0-1 backpack Problems
# Include <cstdio> # include <iostream> using namespace std; # define MAX_N 100 # define MAX_W 1000int n, W; // Select part of int rec (int I, int j) {int res; if (I = n) res = 0; whose total weight is less than j from item I; // else if (j <w [I]) res = rec (I + 1, j ); // unable to select this item else res = max (rec (I + 1, j), rec (I + 1, j-w [I]) + v [I]); // select the largest return res in the case of selection or not;} void solve () {printf ("% d \ n", rec (0, w);} int main () {printf ("n W: \ n"); scanf ("% d", & n, & W ); for (int I = 0; I <n; I ++) {printf ("w [% d] v [% d]: \ n", I, I ); scanf ("% d", & w [I], & v [I]);} solve (); return 0 ;}
Optimization-memory-based search
#include <cstdio>#include <iostream>#include <memory.h>using namespace std;#define MAX_N 100#define MAX_W 1000int n,W;int w[MAX_N],v[MAX_N];int dp[MAX_N+1][MAX_W+1];int rec(int i,int j){ if(dp[i][j]>=0) return dp[i][j]; int res; if(i==n) res=0; else if(j<w[i]) res=rec(i+1,j); else res=max(rec(i+1,j),rec(i+1,j-w[i])+v[i]); return dp[i][j]=res;}void solve(){ memset(dp,-1,sizeof(dp)); printf("%d\n",rec(0,W));}int main(){ printf("n W:\n"); scanf("%d %d",&n,&W); for(int i=0;i<n;i++) { printf("w[%d] v[%d]:\n",i,i); scanf("%d %d",&w[i],&v[i]); } solve(); return 0;}
Dual Loop
#include <cstdio>#include <iostream>using namespace std;#define MAX_N 100#define MAX_W 1000int n,W;int w[MAX_N],v[MAX_N];int dp[MAX_N+1][MAX_W+1];void solve(){ for(int i=n-1;i>=0;i--) { for(int j=0;j<=W;j++) { if(j<w[i]) dp[i][j]=dp[i+1][j]; else dp[i][j]=max(dp[i+1][j],dp[i+1][j-w[i]]+v[i]); } } printf("%d\n",dp[0][W]);}int main(){ printf("n W:\n"); scanf("%d %d",&n,&W); for(int i=0;i<n;i++) { printf("w[%d] v[%d]:\n",i,i); scanf("%d %d",&w[i],&v[i]); } solve(); return 0;}