

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


ECS122A Handout The 0-1 Knapsack Problem
Problem statement. A thief robbing a store finds n items; the ith item is worth vi dollars and weights wi pounds. He wants to take as valuable a load as possible, but he can carry at most W pounds in his knapsack. Here vi, wi and W are all positive integers. What items should be taken? Formally, the problem can be stated as follws:
Given: n items of values v 1 , v 2 ,... , vn and of the weight w 1 , w 2 ,... , wn, and a total weight W , where vi, wi and W are positive integers. Find: a subsect S ⊆ { 1 , 2 ,... , n} of the items such that ∑
i∈S
wi ≤ W and
∑
i∈S
vi is maximized.
This is called the 0-1 knapsack problem because each item must either be taken or left behind; the thief cannot take a fractional amount of an item or take an item more than once. The knapsack problem is an abstraction of many real problems, from investing to telephone routing.
Dynamic Programming.
c[i, w] =
0 if i = 0 or w = 0 max (vi + c[i − 1 , w − wi], c[i − 1 , w]) if i > 0 and wi ≤ w c[i − 1 , w] if i > 0 and wi > w
This says that the value of a solution for item i is
This is, if the thief picks item i, he takes vi value, and he can choose from items 1...i − 1 up to the weight limit w − wi, and get c[i − 1 , w − wi] additional value. On the other hand, if he decides not to take item i, he can choose from items 1...i − 1 up to the weight limit w, and get c[i − 1 , w] value. The better of these two choices should be made.
Dynamic-0-1-Knapsack(v,w,n,W) for w = 0 to W c[0,w] = 0 for i = 1 to n c[i,0] = 0 for w = 1 to W if w[i] <= w then if v[i] + c[i-1,w-w[i]] > c[i-1,w] then c[i,w] = v[i] + c[i-1,w-w[i]] else c[i,w] = c[i-1,w] else c[i,w] = c[i-1,w]