The 01 Knapsack problem Knapsack of capacity W
The 0/1 Knapsack problem Knapsack of capacity W W
The 0/1 Knapsack problem 3 4 5 8 10 W=20
The 0/1 Knapsack problem 3 5 4 8 10 26 W=20
A natural greedy algorithm 3 3/2= 1. 5 4 4/3 =1. 3 5 5/4 =1. 25 8 8/5 =1. 6 10 10/9 =1. 1 W=20
A natural greedy algorithm 4 4/3 =1. 3 5 5/4 =1. 25 8 8/5 =1. 6 W=20 10 10/9 =1. 1 3
A natural greedy algorithm 4 5 W=20 10 4/3 =1. 3 5/4 =1. 25 10/9 =1. 1 8 3
A natural greedy algorithm 5 10 5/4 =1. 25 10/9 =1. 1 4 8 3 W=20
A natural greedy algorithm 10 5 8 10/9 =1. 1 4 3 W=20
A natural greedy algorithm 5 10 14 Suboptimal ! 10/9 =1. 1 8 4 3 20 W=20
Fractional Knapsack 5 10 14 10/9 =1. 1 8 4 3 W=20
Fractional Knapsack 10 5 14 8 4 Can prove its optimal for fraction Knapsack 3 26. 6 W=20
A recursive solution ? Knapsack of capacity W W
A recursive solution Knapsack of capacity W
A recursive solution
Overlapping substructures 5, 7 4, 6 3, 7 2, 7 3, 5 2, 4 1, 4 2, 5 3, 6 2, 2 2, 6 3, 4 2, 3 1, 4 2, 4 1, 4 2, 1
Terrible running time
Fill a table with solutions to all subproblems iW 1 2 3 4 0 1 2 3 4 5
Initialization iW 0 1 2 3 4 5 0 0 0 0 1 2 3 4 B[0, w]=0
Initialization B[i, 0]=0 iW 0 1 2 3 4 5 0 0 0 0 1 0 2 0 3 0 4 0
Fill row by row iW 0 1 2 3 4 5 0 0 0 0 1 0 2 0 3 0 4 0
Fill row by row iW 0 1 2 3 4 5 0 0 0 0 1 0 0 3 3 2 0 3 0 4 0
Fill row by row iW 0 1 2 3 4 5 0 0 0 0 1 0 0 3 3 2 0 0 3 4 4 7 3 0 4 0
Fill row by row iW 0 1 2 3 4 5 0 0 0 0 1 0 0 3 3 2 0 0 3 4 4 7 3 0 0 3 4 5 7 4 0
Fill row by row iW 0 1 2 3 4 5 0 0 0 0 1 0 0 3 3 2 0 0 3 4 4 7 3 0 0 3 4 5 7 4 0 0 3 4 5 7
P-code
How do we compute the items ? • The information is in the table
Find the Knapsack iW 0 1 2 3 4 5 0 0 0 0 1 0 0 3 3 2 0 0 3 4 4 7 3 0 0 3 4 5 7 4 0 0 3 4 5 7
Find the Knapsack iW 0 1 2 3 4 5 0 0 0 0 1 0 0 3 3 2 0 0 3 4 4 7 3 0 0 3 4 5 7 4 0 0 3 4 5 7
Find the Knapsack iW 0 1 2 3 4 5 0 0 0 0 1 0 0 3 3 2 0 0 3 4 4 7 3 0 0 3 4 5 7 4 0 0 3 4 5 7
Running time •
- Slides: 30