0-1 backpack problems:
There are N items and a backpack with a capacity of V. The weight of the I-th item is w [I], and the value is v [I]. Solving which items are loaded into a backpack can make the total weight of these items not exceed the size of the backpack, and the total value is the largest.
This problem is characterized by: each item has only one item, and you can choose to put it or not.
Basic idea of algorithms:
The 0-1 backpack is a classic dynamic planning problem. Using the idea of dynamic planning, the sub-problem is: f [I] [c], which indicates the maximum value that a backpack with a capacity of c can obtain when I items are placed.
The state transition equation is: f [I] [c] = max {f [i-1] [c], f [i-1] [c-w [I] + v [I]} //This equation is very important. Basically all the equations related to the backpack are derived from it.
Note: For item I, there are two options in the optimal solution: adding a backpack or not adding a backpack. If item I is attached to a backpack, f [I] [c] = f [i-1] [c-w [I] + v [I]; if the item is not attached to a backpack, f [I] [c] = f [i-1] [c];
Therefore, the greatest solution of f [I] [c] is the one in the two options.
Code:
# Include <iostream> # include <algorithm> # include <vector>/*** Knapsack problem * // *** [getMostValue obtains maximum value] * @ param Weight [item weight array] * @ param Value item Value array * @ param cap backpack capacity * @ param size number of items * @ return maximum Value */int getMostValue (int * Weight, int * Value, int cap, int size) {int array [cap + 1], tmp [cap + 1]; for (int I = 0; I <cap + 1; I ++) {array [I] = 0; tmp [I] = 0 ;}for (int I = 0; I <size; I ++) {// itemfor (in T j = 1; j <cap + 1; j ++) {// weightif (j> = Weight [I]) array [j] = (tmp [j]> tmp [j-Weight [I] + Value [I])? Tmp [j] :( tmp [j-Weight [I] + Value [I]); std: cout <array [j] <"\ t ";} for (int k = 0; k <cap + 1; k ++) tmp [k] = array [k]; std: cout <std: endl ;} return array [cap];} int main () {int Weight [] = {60,100,120, 3}; int Value [] = {}; int mostvalue = getMostValue (Weight, value, 5, 3); std: cout <"max value is" <mostvalue <std: endl ;}
0-1 backpack problems