Saturday, February 11, 2012

Dynamic Programming: Unbounded knapsack problem


During a robbery, a burglar finds much more loot than he had expected and has to decide what to take. His bag (or knapsack) will hold a total weight of at most W pounds. There are n items to pick from, of weight w1.....wn and dollar value v1.....vn. What's the most valuable combination of items he can fit into his bag?


For instance, take W = 10 and
Item Weight Value
1            6      $30
2            3      $14
3            4      $16
4            2      $9


Let K(w) = max value achievable with a knapsack of capacity w.


Now if the optimal solution to K(w) includes i, then removing this item from knapsack leaves an optimal solution to K(w-w[i])+v[i], for some i.
As we dont know which i, so we will try all the possibilities.
K(w) = MAX {K(w-w[i] + v[i]} for i:w[i]<w


The maximum over an empty set is 0.


K(0) = 0
for w = 1 to W:
K(w) = max{K(w - wi) + vi: wi <= w}
return K(W)




This algorithm fills in a one-dimensional table of length W + 1, in left-to-right order. Each entry can take up to O(n) time to compute, so the overall running time is O(nW). As always, there is an underlying dag. Try constructing it, and you will be rewarded with a startling insight: this particular variant of knapsack boils down to finding the longest path in a dag!


Code Input:
int [] W = {6, 3, 4, 2};
int [] V = {30, 14, 16, 9};
int M = 10;


Code output:
Printing knapsack for different Ws:
0 0 9 14 18 23 30 32 39 44 48 
Optimal value for unbounded knapsack: 48



3 comments:

  1. I know this article is rather old but I have a similiar problem to solve. Why do you call your problem unbounded? The first solution (not the source code) makes sense only if the items are bounded to 1 or 0, so its not unbounded.
    For the following problem I have to find the solution manually:
    max = 370a+150b+190c+12d
    s.t. 440a+180b+250c+17d <= 9540
    obj-function with value and constraint with weight. I dont know how to construct a table to find the optimal solution. Any clue?

    ReplyDelete
  2. @Frederik: You are right. this code is for bounded problem and that also with bound as 1. For your case, we need to slightly modify the code

    best = Math.max(K[w-W[i]] + V[i], best);

    should be replaced by a loop iterating over the no. of times a value repeats and finally breaking by assigning the maximum value possible.

    ReplyDelete
  3. hey Arjun)

    you mind to show example of what you mentioned above?)

    i mean iterating loop for the problem Frederik stated!

    cheers, mate)

    ReplyDelete