Unit 4 - 4 Dynamic Programming
Unit 4 - 4 Dynamic Programming
SE 208
Unit 4 -4 Dynamic Programming
Matrix Chain Multiplication
Divyashikha Sethia
Divyashikha@dtu.ac.in
DTU
Matrix-chain Multiplication
• Suppose we have a sequence or chain
A1, A2, …, An of n matrices to be
multiplied
– That is, we want to compute the product
A1A2…An
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
Divyashikha Sethia (DTU)
11-5
Matrix-chain Multiplication …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
MATRIX-CHAIN-ORDER(p[ ], n)
for i ← 1 to n Takes O(n3) time
m[i, i] ← 0
Requires O(n 2) space
for l ← 2 to n
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
Divyashikha Sethia (DTU)
11-14
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