0% found this document useful (0 votes)
4 views13 pages

Knapsack

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

Knapsack

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Knapsack Problem by DP

Given n items of
integer weights: w1 w2 … wn
values: v1 v2 … vn
a knapsack of integer capacity W
find most valuable subset of the items that fit into the knapsack

Consider instance defined by first i items and capacity j (j  W).


Let V[i,j] be optimal value of such instance. Then
max {V[i-1,j], vi + V[i-1,j- wi]} if j- wi  0
V[i,j] =
V[i-1,j] if j- wi < 0

Initial conditions: V[0,j] = 0 and V[i,0] = 0


Recurrence equation
Knapsack Problem by DP (example)
Example: Knapsack of capacity W = 5
item weight value
1 2 $12
2 1 $10
3 3 $20
4 2 $15 capacity j
0 1 2 3 4 5
0
w1 = 2, v1= 12 1
w2 = 1, v2= 10 2
w3 = 3, v3= 20 3
w4 = 2, v4= 15 4 ?
Example 3: Path counting

Consider the problem of counting the number of shortest


paths from point A to point B in a city with perfectly
horizontal streets and vertical avenues
1

B
Example 4: Coin-collecting by robot
Several coins are placed in cells of an n×m board. A robot,
located in the upper left cell of the board, needs to collect as
many of the coins as possible and bring them to the bottom
right cell. On each step, the robot can move either one cell to
the right or one cell down from its current location.
1 2 3 4 5 6

5
Solution to the coin-collecting problem
Let F(i,j) be the largest number of coins the robot can collect
and bring to cell (i,j) in the ith row and jth column.

The largest number of coins that can be brought to cell (i,j):

from the left neighbor ?


from the neighbor above?

The recurrence:
F(i, j) = max{F(i-1, j), F(i, j-1)} + cij for 1 ≤ i ≤ n, 1 ≤ j ≤ m
where cij = 1 if there is a coin in cell (i,j), and cij = 0 otherwise

F(0, j) = 0 for 1 ≤ j ≤ m and F(i, 0) = 0 for 1 ≤ i ≤ n.


Solution to the coin-collecting problem
(cont.)
F(i, j) = max{F(i-1, j), F(i, j-1)} + cij for 1 ≤ i ≤ n, 1 ≤ j ≤ m
where cij = 1 if there is a coin in cell (i,j), and cij = 0 otherwise
F(0, j) = 0 for 1 ≤ j ≤ m and F(i, 0) = 0 for 1 ≤ i ≤ n.
1 2 3 4 5 6

5
Example

You might also like