Professional Documents
Culture Documents
Chain Matrix Multiplication Handout
Chain Matrix Multiplication Handout
Outline
Review of matrix multiplication.
The chain matrix multiplication problem.
A dynamic programming algorithm for chain matrix
multiplication.
A1 A2 6= A2 A1
Example
For p = 5, q = 4, r = 6 and s = 2,
mult[(AB)C ] = 180,
mult[A(BC )] = 88.
A big difference!
Example
A1 A2 A3 A4 = (A1 A2 )(A3 A4 ) = A1 (A2 (A3 A4 )) = A1 ((A2 A3 )A4 )
= ((A1 A2 )A3 )(A4 ) = (A1 (A2 A3 ))(A4 )
Yes – DP
Version of October 26, 2016 Chain Matrix Multiplication 8 / 27
Outline
Original Problem:
Determine minimal cost multiplication sequence for A1..n .
Subproblems: For every pair 1 ≤ i ≤ j ≤ n:
Determine minimal cost multiplication sequence for
Ai..j = Ai Ai+1 · · · Aj .
Note that Ai..j is a pi−1 × pj matrix.
n
= Θ(n2 ) such subproblems. (Why?)
There are 2
How can we solve larger problems using subproblem solutions?
Question
How do we decide where to split the chain (what is k)?
Proof.
If j = i, then m[i, j] = 0 because, no mutiplications are required.
If i < j, note that, for every k, calculating Ai..k and Ak+1..j
optimally and then finishing by multiplying Ai..k Ak+1..j to get Ai..j
uses (m[i, k] + m[k + 1, j] + pi−1 pk pj multiplications.
The optimal way of calculating Ai..j uses no more than the worst
of these j − i ways so
Proof.
For the other direction, note that an optimal sequence of
multiplications for Ai..j is equivalent to splitting Ai..j = Ai..k Ak+1..j
for some k, where the sequences of multiplications to calculate
Ai..k and Ak+1..j are also optimal. Hence, for that special k,
Recurrence:
S0: Initialization
Idea: Maintain an array s[1..n, 1..n], where s[i, j] denotes k for the
optimal splitting in computing Ai..j = Ai..k Ak+1..j .
Question
How to Recover the Multiplication Sequence using s[i, j]?
Complexity: The loops are nested three levels deep. Each loop index takes on
≤ n values. Hence the time complexity is O(n3 ). Space complexity is Θ(n2 ).
Version of October 26, 2016 Chain Matrix Multiplication 27 / 27