Dynamic Programming
Dynamic Programming
Anjali Mohapatra.
Introduction
• Optimization problem: there can be many possible solution. Each
solution has a value, and we wish to find a solution with the optimal
(minimum or maximum) value
11-6
Matrix-chain Multiplication …contd
11-8
Algorithm to Multiply 2 Matrices
Input: Matrices Ap×q and Bq×r (with dimensions p×q and q×r)
Result: Matrix Cp×r resulting from the product A·B
MATRIX-MULTIPLY(Ap×q , Bq×r)
1. for i ← 1 to p
2. for j ← 1 to r
3. C[i, j] ← 0
4. for k ← 1 to q
5. C[i, j] ← C[i, j] + A[i, k] · B[k, j]
6. return C
Scalar multiplication in line 5 dominates time to compute
CNumber of scalar multiplications = pqr
11-9
Matrix-chain Multiplication …contd
11-12
Dynamic Programming Approach
…contd
11-13
Illustration of Optimal
SubStructure Minimal
Cost_A1..6 + Cost_A7..9+p0p6p9
A1A2A3A4A5A6A7A8A9
((A1A2)(A3((A4A5)A6))) ((A7A8)A9)
Dynamic Programming Approach …
contd
11-15
Dynamic Programming Approach …
contd
11-16
Dynamic Programming Approach …
contd
0 if i=j
m[i, j ] =
min {m[i, k] + m[k+1, j ] + pi-1pk pj } if i<j
i ≤ k< j
11-17
Step 3
• Computing the optimal costs
– How much sub-problems in total?
• One for each choice of i and j satisfying 1 i j n
(n2)
– MATRIX-CHAIN-ORDER(p)
• Input: a sequence p= <P1, P2,…, Pn> (length[p] = n+1)
• Try to fill in the table m in a manner that corresponds
to solving the parenthesization problem on matrix
chains of increasing length
• Lines 4-12: compute m[i, i+1], m[i, i+2], … each time
Dynamic Programming Approach …
contd
11-19
Algorithm to Compute Optimal Cost
Input: Array p[0…n] containing matrix dimensions and n
Result: Minimum-cost table m and split table s
MATRIX-CHAIN-ORDER(p[ ], n)
for i ← 1 to n Takes O(n3) time
m[i, i] ← 0
for l ← 2 to n Requires O(n2) space
for i ← 1 to n-l+1
j ← i+l-1
m[i, j] ←
for k ← i to j-1
q ← m[i, k] + m[k+1, j] + p[i-1] p[k] p[j]
if q < m[i, j]
m[i, j] ← q
s[i, j] ← k
return m and s
11-20
O(n3), (n3) (n3) running time
(n2) space
l =3
l=2
35*15*5=2625 10*20*25=5000
m[3,4]+m[5,5] + 15*10*20
=750 + 0 + 3000 = 3750
m[3,5] = min
m[3,3]+m[4,5] + 15*5*20
=0 + 1000 + 1500 = 2500
Step 4
• Constructing an optimal solution
– Each entry s[i, j] records the value of k such
that the optimal parenthesization of AiAi+1…Aj
splits the product between Ak and Ak+1
– A1..n A1..s[1..n] As[1..n]+1..n
– A1..s[1..n] A1..s[1, s[1..n]] As[1, s[1..n]]+1..s[1..n]
– Recursive…
Constructing Optimal Solution
• Our algorithm computes the minimum-
cost table m and the split table s
• The optimal solution can be constructed
from the split table s
– Each entry s[i, j ]=k shows where to split the
product Ai Ai+1 … Aj for the minimum cost
11-25
Elements of Dynamic
Programming
Optimal substructure
Overlapping subproblems