The 0-1 knapsack problem is described as follows:
There is a backpack with a capacity of V, and some items. These items have two properties, Volume W and value V, and only one for each item. Ask for the maximum value of the item that is worth as much as possible with this back, and the backpack may not be filled. Because there are two possible cases for each item in the optimal solution, either in the backpack or absent (there are 0 items or 1 in the backpack), we call this problem the 0-1 knapsack problem.
Use dp[i][j] to indicate that the top I items in the overall product does not exceed J, the maximum value placed in the backpack. Thus, the state transfer equation can be introduced:
DP[0][J] = 0;
DP[I][J] = Max{dp[i-1][j-v[i]] + w[i],dp[i-1][j]};
The above formula should be well understood, when the volume of item I is less than the current remaining volume, it can be loaded into the backpack, then dp[i][j] = Dp[i-1][j-v[i]]+w[i]. On the other hand, can not be transferred to the backpack, dp[i][j] = dp[i-1][j].
#include <iostream>using namespacestd;#defineMAXSIZE 100intW[maxsize];intV[maxsize];intMAXV;intN;intDp[maxsize][maxsize];intMaxintAintb) { if(A >b)returnA; Else returnb;}intMain () {CIN>> N >>MAXV; for(inti =1; I <= N; i++) {cin>> W[i] >>V[i]; } for(inti =0; I <= MAXV; i++) dp[0][i] =0; for(inti =1; I <= N; i++) { //only when J >= W[i],dp[i][j] can select the maximum value for(intj = MAXV; J >= W[i]; j--) {Dp[i][j]= Max (Dp[i-1][J], Dp[i-1][j-w[i]] +V[i]); } //when J < W[i], stating that the item I is not able to transfer to the backpack, so dp[i][j] = Dp[i-1][j] for(intj = W[i]-1; J >=0; j--) Dp[i][j]= Dp[i-1][j]; } cout<< DP[N][MAXV] <<Endl; return 0;}
Dynamic planning-0-1 knapsack problem