Lecture 21ppt
Lecture 21ppt
1 4
A1 2 A4 A5
A2 A3
Algorithms – p. 393
Chain Matrix Multiply Algorithm
MATRIX - CHAIN(p, N)
1 = 1, N
for i
2 do m[i, i] ← 0
3 for L = 2, N
4 do
5 for i= 1, n − L + 1
6 do j ← i + L − 1
7 m[i, j] ← ∞
8 for k = 1, j − 1
9 do t ← m[i, k] + m[k + 1, j] + pi−1 · pk · pj
10 if (t < m[i, j])
11 then m[i, j] ← t; s[i, j] ← k
Algorithms – p. 394
Chain Matrix Multiply Algorithm
Analysis
• There are three nested loops.
• Each loop executes a maximum n times.
• Total time is thus Θ(n3 ).
Algorithms – p. 395
Chain Matrix Multiply Algorithm
1 if (i = j)
2 then return A[i]
3 else k ← s[i, j]
4 X ← MULTIPLY(i, k)
5 Y ← MULTIPLY(k + 1, j)
6 return X · Y
Algorithms – p. 396
0/1 Knapsack Problem
• Given a knapsack with maximum capacity W,
and a set S consisting of n items
• Each item i has some weight wi and value
value vi (all wi , vi and W are integer values)
• Problem: How to pack the knapsack to
achieve maximum total value of packed
items?
Algorithms – p. 397
0/1 Knapsack Problem
Algorithms – p. 399
0/1 Knapsack Problem
Algorithms – p. 400
0/1 Knapsack Problem
• Can we do better?
• Yes, with an algorithm based on dynamic
programming
• We need to carefully identify the subproblems
Algorithms – p. 401
0/1 Knapsack Problem
• Let us try this:
• If items are labelled 1, 2, . . . , n, then a
subproblem would be to find an optimal
solution for
Sk = items labelled 1, 2, . . . , k
Algorithms – p. 402
0/1 Knapsack Problem
• This is a valid subproblem definition.
• The question is: can we describe the final
solution Sn in terms of subproblems Sk ?
• Unfortunately, we cannot do that. Here is why.
Algorithms – p. 403
0/1 Knapsack Problem
Item wi vi
Solution S4 1 2 3
• Items chosen are 1, 2, 3, 4 2 3 4
• Total weight: 2 + 3 + 4 + 5 = 14 3 4 5
• Total value: 3 + 4 + 5 + 8 = 20
4 5 8
5 9 10
Algorithms – p. 404
0/1 Knapsack Problem
Item wi vi
Solution S5
1 2 3
• Items chosen are 1, 3, 4, 5
2 3 4
• Total weight: 2 + 4 + 5 + 9 = 20
• Total value: 3 + 5 + 8 + 10 = 26
3 4 5
4 5 8
S4 is not part of S5!!
5 9 10
Algorithms – p. 405
0/1 Knapsack Problem
• The solution for S4 is not part of the solution
for S5 .
• So our definition of a subproblem is flawed
and we need another one.
Algorithms – p. 406
0/1 Knapsack Problem: DP Approach
Algorithms – p. 407
0/1 Knapsack Problem: DP Approach
• We construct a matrix V[0 . . . n, 0 . . . W].
• For 1 ≤ i ≤ n, and 0 ≤ j ≤ W, V[i, j] will store
the maximum value of any set of objects
{1, 2, . . . , i} that can fit into a knapsack of
weight j.
• V[n, W] will contain the maximum value of all
n objects that can fit into the entire knapsack
of weight W.
Algorithms – p. 408
0/1 Knapsack Problem: DP Approach
• To compute entries of V we will imply an
inductive approach.
• As a basis, V[0, j] = 0 for 0 ≤ j ≤ W since if
we have no items then we have no value.
• We consider two cases:
Algorithms – p. 409