Wednesday we looked at how to find the highest value that can be
packed into a knapsack with capacity ,
items with weights
, ...,
, and values
, ...,
. That algorithm
told us how find the highest value we can pack into the
knapsack, but now which items to pack. Add an array
(the index
of the last item packed into an optimal packing not exceeding capacity
), and we can track the choices of what fills up an ideal knapsack:
V[0] = 0; for (int j = 1; j <= C; j++) { V[j] = V[j-1]; L[j] = L[j-1]; for (int i = 0; i < n; i++) { if (w[i] <= j && v[i] + V[j-w[i]] > V[j]) { V[j] = v[i] + V[j-w[i]]; L[j] = i; } } }Now we can work backwards from