"Introduction to Algorithms" 0-1 knapsack problem

Source: Internet
Author: User


        One, 0-1 knapsack problem Description:


Known: Thieves in the shop to steal things, thieves only with a maximum load-bearing w backpack, the store has n goods, the first item of the weight is weight[i], the price is value[i].


Limitations: each commodity only one, you can choose to take or not to take, can not be divided, can not only take a part of the product (so called 0-1,0 is not taken, 1 of the entire take away, and a product has and only one piece to take away)


Questions: How much money can be taken without exceeding the maximum load-bearing capacity of the backpack.


The calculation of the 0-1 knapsack problem corresponds to the score knapsack problem, the items in the score knapsack problem can be taken part of, that is, can be split, not like 0-1 backpack, or all take away, or do not take. The problem of fractional knapsack can be solved by greedy algorithm, and the 0-1 knapsack problem should be planned dynamically, because 0-1 knapsack problem must consider the free space of knapsack.


There is a problem called complete knapsack, complete knapsack problem Unlike here, there are many pieces of each product ~ ~


Anyway, first to see how to solve the problem of 0-1 knapsack.



       Second, the solution

State transition equation:

If for I and the maximum load bearing w backpack, the maximum benefit is value_of_all[i][w], in fact, Value_of_all[i][w] The key is not to take this article I goods.


① If you take, you must calculate the price of the item I, and then add the w-weight[i] load-bearing backpack to take the other I-1 items of the maximum benefit;


② if not take, then value_of_all[i][w]=value_of_all[i-1][w], because this is equivalent to use W load-bearing backpack to fetch i-1 pieces of goods.


So it's easier to give the state transition equation:


Value_of_all[i][w] = max{value_of_all[i-1][w-weight[i]]+value[i], value_of_a LL[I-1][W]}

Then to consider the boundary conditions, for the first commodity, if weight[i]>w, it is certainly not fit, then value_of_all[i][w]=value_of_all[i-1][w], Because then the item I is bound to not fit, otherwise, it is necessary to refer to the above state transfer equation to calculate. Note that for total revenue Value_of_all[i][w], either i=0 or w=0, the value is 0.


With the above analysis, it is not difficult to give the code:

/* * 01 knapsack problem, can only be solved by dynamic programming: * * The optimal sub-problem is divided into: V[i,w]=max (V[i-1,w-wi]+vi, v[i-1,w]), wherein I is included in the product of I, W means the maximum load of the backpack * * Vi means the price of the goods in Part I, Wi denotes the weight of the first commodity * * v[i,w] means that in the case of I commodity, backpack load-bearing maximum of W, the value of the goods can be taken out of the maximum value * * The above formula is a choice, whether to carry the commodity I, V[i-1,w-wi]+vi said it will carry the proceeds of the first commodity , while v[i-1,w] means that I must not take the first commodity * only one or more of the proceeds of other i-1 species. And our v[i,w] will be obtained in the maximum value of the above two values * * * We can easily know, when wi>w, must not be able to take the item I goods *///merchandise There are 5 pieces # # # N 5//Backpack is weight # # W 12int value_of _all[n + 1][w + 1] = {0};  Because to take the 1~n, the weight to take to 1~w//the price of the article I commodity, the array of 0 subscript element omitted int value[n + 1] = {0, 6, 3, 5, 4, 6};//The weight of the item I, 0 subscript element omitted int weight[n + 1] = {0, 2, 2, 6, 5, 4};int& Max (int& A, int& b) {return a > B? a:b;} void _01_packages () {for (int i = 0; I <= N; i++) {value_of_all[i][0] = 0;} for (int w = 0; w <= N; w++) {value_of_all[0][w] = 0;} /* * Formula: * * Value_of_all[i][w]=max{value_of_all[i-1][w-w[i]]+value[i], Value_of_all[i-1][w]} */for (int i = 1; I <= N ; i++) {for (int w = 1; w <= W; w++) {if (Weight[i] > W) {value_of_all[i][w] = Value_of_all[i-1][w];} else {value_of_all[i][w] =value_of_all[i-1][w]> (Value_of_all[i-1][w-weight[i]] + value[i])? value_of_all[i-1][ W]:(Value_of_all[i-1][w-weight[i]] + value[i]);}}} cout << "The total value of the selected product is maximum:" << value_of_all[n][w] << Endl;}


        third, the inverse push the concrete optimal solution commodity

After the above function, output VALUE_OF_ALL[N][W] value, that is, when there are N items, the backpack capacity is W, the maximum benefit, but at this time we also want to know when the maximum benefit, we actually took the few goods? Then we'll look at the state transition equation:


value_of_all[i][w] = Max{value_of_all[i-1][w-weight[i]]+value[i], Value_of_all[i-1][W]}


What we want to know is the I value that was taken when the first parameter in the MAX function in the formula above is large, because this is when we "get" the item "I". We can verify in turn, see value_of_all[i][w] is not equal to Value_of_all[i-1][w-weight[i]] + value[i], if it is we will put this I value into the stack, if not omitted; Subtract the value of I by one, Then continue with the above verification until i=1.


And then put the stack I value above the stack in turn, you can get from I=1 to n the process, in order to take what products.

/* * Print 01 knapsack problem The best proceeds of the product selection composition * Param: * N represents the number of items, W represents the weight of the backpack */void Print (stack<int>* result, int n, int w) {for (int i = N I >= 1; i--) {if (Value_of_all[i][w] > Value_of_all[i-1][w]) {Result->push (i);}} cout << "Selected:" while (!result->empty ()) {cout << "<< result->top () <<"; Result->pop ();} cout << "Pieces of goods" << Endl;} int main () {_01_packages (); stack<int>* result = new stack<int>; Print (result, N, W);d elete Result;result = Null;return 0;}


Output Result:









"Introduction to Algorithms" 0-1 knapsack problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.