Turn from: Backpack Long talk Tianyi Cui
Details of the initialization
There are actually two different kinds of questions that we see in the knapsack problem of finding the best solution. Some of the topics require "Just fill the backpack" when the optimal solution, and some of the problems are not required to fill the backpack. One way of distinguishing between the two methods of asking is to make a difference when initializing.
If this is the first method of asking for a full backpack, then at initialization the F[0] is set to-∞ except for the 0 other F[1..V], so that the resulting f[n] is the optimal solution for a packed backpack.
If it is not required to fill the backpack, but only want the price as large as possible, the initialization should be F[0..V] all set to 0.
Why is it? It can be understood that the initialized F-array is in fact the legal state when no item can be placed in the backpack. If the backpack just fills up, then only the capacity of 0 of the backpack may be worth 0 of nothing "exactly full", the other capacity of the backpack are not legal solution, belong to the undefined state, their values should be-∞. If the backpack does not have to be filled, then any capacity backpack has a legitimate solution "nothing", the value of this solution is 0, so the initial state of the value is all 0.
This tip can be generalized to other types of knapsack problems, and the initialization before state transfer is no longer explained later.
A constant optimization
There is a for v=v in the preceding pseudo-code: 1, the lower limit of this cycle can be improved.
Because only need the last f[v] value, backward push the previous item, in fact as long as know F[v-w[n]] can. And so on, to the J backpack, actually only need to know to f[v-sum{w[j. N]}], that is, the code in the
For I=1..N
For V=v. 0
can be changed into
For I=1..N
Bound=max{v-sum{w[i. N]},c[i]}
For V=v. Bound
This is useful for V when it is relatively large.
01 Knapsack initialization details and the improvement of the cycle limit