Dynamic Programming: The Matrix Chain Algorithm: Andreas Klappenecker (Partially Based On Slides by Prof. Welch)
Dynamic Programming: The Matrix Chain Algorithm: Andreas Klappenecker (Partially Based On Slides by Prof. Welch)
!
[partially based on slides by Prof. Welch]
Matrix Chain Problem
A x (BxC) or (AxB) x C
Matrices
An n x m matrix A over the real numbers is a rectangular array of
nm real numbers that are arranged in n rows and m columns.
!
a11 a12
A =
a21 a22
a31 a32
!
!
Let A be an n x m matrix
B an m x p matrix
A: 30 x 1
B: 1 x 40
C: 40 x 10
D: 10 x 25
• Basis: M(i,i) = 0.
• best case cost for computing the product of the two pieces
P1 P2
•minimum cost to compute P1 is M(i,k)
•minimum cost to compute P2 is M(k+1,j)
•cost to compute P1· P2 is di-1dkdj
Step 2: Find Dependencies
Among Subproblems
M: 1 2 3 4 5
1 0 GOAL!
2 n/a 0
computing the pink
3 n/a n/a 0 square requires the
4 n/a n/a n/a 0 purple ones: to the
left and below.
5 n/a n/a n/a n/a 0
Defining the Dependencies
M(i,j), M(i+1,j),…,M(j,j)
Step 3: Identify Order for
Solving Subproblems
Recall the dependencies between subproblems just found
Solve the subproblems (i.e., fill in the table entries) this way:
M: 1 2 3 4 5
1 0 4
3
2
2 n/a 0 1
3 n/a n/a 0
4 n/a n/a n/a 0
5 n/a n/a n/a n/a 0
Pseudocode
for i := 1 to n do M[i,i] := 0
endfor
endfor
running time O(n3)
endfor
Example
M: 1 2 3 4
1: A is 30x1
1 0 1200 700 1400 2: B is 1x40
3: C is 40x10
2 n/a 0 400 650 4: D is 10x25
3 n/a n/a 0 10,000 BxC: 1x40x10
(BxC)xD:
Bx(CxD):
... + 10,000
Keeping Track of the Order
• It's fine to know the cost of the cheapest order, but what is that
cheapest order?
• After M and S have been filled in, then call a recursive algorithm
on S to print out the actual order
Modified Pseudocode
for i := 1 to n do M[i,i] := 0
M[i,j] := infinity
for k := i to j-1 to
endfor
keep track of cheapest split point
endfor
found so far: between Ak and Ak+1
endfor
Example
M: 1 2 3 4
1: A is 30x1
S: 1 0 1200 700 1400 2: B is 1x40
1 1 1
3: C is 40x10
2 n/a 0 400 2 650 4: D is 10x25
3
3 n/a n/a 0 10,000
3 A x (BCD)
A x ((BxC) x D)
Using S to Print Best Ordering
Print(S,i,j):
else
k := S[i,j]