Professional Documents
Culture Documents
Knapsack PDF
Knapsack PDF
1
0-1 Knapsack Problem
2
0-1 Knapsack Problem
3
Recall of the Divide-and-Conquer
4
The Idea of Dynamic Programming
5
The Idea of Developing a DP Algorithm
6
The Idea of Developing a DP Algorithm
7
Remarks on the Dynamic Programming Approach
8
Developing a DP Algorithm for Knapsack
9
Developing a DP Algorithm for Knapsack
10
Correctness of the Method for Computing 1 278( 6
Lemma: For
" / / , / / ,
1 278( H
6 ; @ A C E
B D 1 27 = " 6
: F 1 27 = " = 6
G
6
Proof: To compute 1 2<8 we note that we have only
two choices for file :
12
Example of the Bottom-up computation
Let
; " and
1 2 3 4
10 40 30 50
5 4 6 3
O P , QSRUT V
XW V 0
1 2 3 4 5 6 7 8 9 10
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 10 10 10 10 10 10
2 0 0 0 0 40 40 40 40 40 50 50
3 0 0 0 0 40 40 40 40 40 50 70
4 0 0 0 50 50 50 50 90 90 90 90
Remarks:
Y The final output is
O [P Z \Q
V]TXW ^_V .
Y
` CQ Zba
The method described does not tell which subset gives the
optimal solution. (It is in this example).
13
The Dynamic Programming Algorithm
g
KnapSack( c SQ RdQ Qfe )
for (R W V to e )
O P VCQhRiTW V ;
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 ;
v return
14
Constructing the Optimal Solution
6
Question: How do we use all the values x#y]y(z*2<8 to
determine the subset of files having the maximum
computing time?
15
Constructing the Optimal Solution
computing time?
If keep[ 5
] is 1, then } " . = We can now repeat
this argument for keep[
= ].
If keep[ H
] is 0, the } ~
ment for keep[
= " ]. and we repeat the argu-
Therefore, the following partial program will output the
elements of :
; ;
for (
; downto
if (keep 2<8
0
6 ; ; "
1)
)
; = 27 6 ;
output i;
16
The Complete Algorithm for the Knapsack Problem
g
KnapSack( c QSRdQ Qfe )
for (R W V to e )
O P VMQhRUTW V ;
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
;
v keep
g
else
OIP ,QhRUTW O P Mp
qQhRUT ;
P ,QRUTW V ;
v keep
W e ;
for (W downto P
ifg (keep ,Q TJW W
)
1)
W i; p R P 3T ;
output
v
O P Q
e T ;
v return
17