Professional Documents
Culture Documents
Knapsack
Knapsack
-tuples of positive
and
, we wish to determine the subset
and
!#" %$&'(*) (of files to store) that
maximizes
.
,+subject to
0/
,+
Remark: This is an optimization problem.
Brute force: Try all
$
possible subsets
6
1 2 : 56 60; ; = >
1 2<8
for
for
/ /
? ,
no item
illegal
10
1 278( 6
" / / , / / ,
H
6
;
@
A
C
E
B
D
=
6
=
=
6
G
"
"
1 278(
1 27
: F 1 27
6
Proof: To compute 1 2<8 we note that we have only
two choices for file :
Lemma: For
=72 " 8 6 .
11
1 2 6H;
for all
278 6
(using iteration,
/ /
row by row.
V[i,w] w=0
i= 0
0
1
0
2
0
3
0
...
...
... W
... 0
bottom
1
2
..
.
n
up
12
;
"
Let
and
O P , QSRUT V
XW V 0
1
2
3
4
0
0
0
0
1
0
0
0
0
0
2
0
0
0
0
0
Remarks:
Y
Y
1
10
5
3
0
0
0
0
50
2
3
4
40 30 50
4
6
3
4
0
0
40
40
50
5
0
10
40
40
50
O [P Z \Q
V]TXW ^_V
6
0
10
40
40
50
7
0
10
40
40
90
8
0
10
40
40
90
9
0
10
50
50
90
10
0
10
50
70
90
` CQ Zba
The method described does not tell which subset gives the
in this example).
optimal solution. (It is
13
c SQ RdQ Qfe )
O P VCQhRiTW V ;
for (R W V to e )
for (W
to )
for (R W P V to e )
if (O R P 3Tj R )
,QkRUTW l mon ` O P Mp
qQhRUTrQ c P 3Tts O P M p
qQhR p R P 3T3T a ;
else
O P ,QkRUTW OIP Mp
qQhRUT ;
O P Que T ;
return
v
g
KnapSack(
w D G.
14
6
The algorithm for computing 1 278
described in
the previous slide does not keep record of which
subset of items gives the optimal solution.
15
If keep[ 5
] is 1, then
=
this argument for keep[
If keep[ H
] is 0, the } ~
= " ].
ment for keep[
; ;
;
downto
for (
1)
0
6
;
; "
if (keep 2<8
; = 27 6 ;
output i;
16
c QSRdQ Qfe )
O P VMQhRUTW V ;
for (R W V to e )
for (W
to )
for (R W P V to e )
P O P C p q
QhR p R P 3T3T O P M p
qQhRUT ))
ifg ((R 3TXj R ) and (c 3Tts
OIP ,QhRUTW c P 3Tts O P Cp
qhQ R p R P 3 T3T ;
P ,QRUTW
;
keep
v
else
g
OIP ,QhRUTW O P Mp
qQhRUT ;
P ,QRUTW V ;
keep
v
W e ;
for (W downto
1)
P
KnapSack(
17