0-1 backpack Problems
Problem description
When a thief steals a store, he finds n items. the I-th item is worth vi yuan and its weight is wi. Assume that both vi and wi are integers. He wants to take away the more valuable the better, but he can only hold up to W lbs of things in his backpack, W is an integer. What kind of things should he take away?
0-1 backpack problems: each item may be taken away or left behind (a 0-1 choice is required ). A thief cannot take only one part of an item or take the same item more than twice.
Some backpack problems: thieves can only take part of an item without making 0-1 choices.
Solution to the 0-1 backpack Problem
The 0-1 knapsack problem is a typical problem with a public sub-structure, but it can only be solved using dynamic planning, rather than using greedy algorithms. In the case of a 0-1 backpack, I chose whether to add an item to the backpack, you must compare the solution of the subproblem that the item is added to with the solution of the subproblem that does not take the item. This approach leads to many overlapping sub-problems that meet the characteristics of dynamic planning. The steps to solve the problem of 0-1 backpacks through dynamic planning are as follows:
0-1 knapsack problem sub-structure: when selecting a given item I, You need to compare the optimal solution of the sub-problem formed by selecting I with the optimal solution of the sub-problem without selecting I. It is divided into two subproblems, select and compare, and select the optimal one.
Recursive process of 0-1 knapsack problems: There are n items, the weight of the backpack is w, C [I] [w] is the optimal solution. That is:
Code:
# Include
# Include # define MAX 1000 using namespace std; int dp [MAX] [MAX]; int record [MAX]; int W; int KnapSack (int n, int w [], int v []) // number of items n, item value v [I], item weight w [I] {int I, j; for (I = 0; I <= n; I ++) // initialize the Boundary Value dp [I] [0] = 0; for (j = 0; j <= W; j ++) dp [0] [j] = 0; for (I = 1; I <= n; I ++) {for (j = 1; j <= W; j ++) {if (j
0; I --) {if (dp [I] [j]> dp [I-1] [j]) {record [I] = 1; j-= w [I];} elserecord [I] = 0;} return dp [n] [W];} int main (int argc, char * argv []) {int n; int I, j; int v [MAX], w [MAX]; cout <"Please input n ="; cin> n; cout <"Please input W ="; cin> W; cout <"Please input value:" <
> V [I]; cout <"Please input weight:" <
> W [j]; cout <"Max value is:" <