Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Weight Value
1
8
3
6
5
5
1
Knapsack problem
There are two versions of the problem:
1. 0-1 knapsack problem
max bi subject to wi W
iT
iT
Defining a Subproblem
Defining a Subproblem
Defining a Subproblem
If items are labeled 1..n, then a subproblem would be
to find an optimal solution for Sk = {items labeled
1, 2, .. k}
Defining a Subproblem
w1 =2 w2 =4
b1 =3 b2 =5
w3 =5
b3 =8
Weight Benefit
w4 =3
b4 =4
?
Max weight: W = 20
For S4:
Total weight: 14
Maximum benefit: 20
w1 =2 w2 =4
b1 =3 b2 =5
w3 =5
b3 =8
w5 =9
b5 =10
For S5:
Total weight: 20
Maximum benefit: 26
wi
bi
10
Item
#
S4
S5
Solution for S4 is
not part of the
solution for S !!!
10
Defining a Subproblem
11
Defining a Subproblem
12
Defining a Subproblem
13
14
or
2) the best subset of Sk-1 that has total weight w-wk plus
the item k
15
Recursive Formula
V [k 1, w]
if wk w
V [ k , w]
max{V [k 1, w],V [k 1, w wk ] bk } else
16
Running time
for w = 0 to W
O(W)
V[0,w] = 0
for i = 1 to n
V[i,0] = 0
Repeat n
for i = 1 to n
for w = 0 to W
O(W)
< the rest of the code >
times
18