Algorithms and Data Structures: Dynamic Programming Matrix-Chain Multiplication
Algorithms and Data Structures: Dynamic Programming Matrix-Chain Multiplication
Greedy Algorithms
Idea: Find solution by always making the choice that looks
optimal at the moment — don’t look ahead, never go back.
Examples: Prim’s algorithm, Kruskal’s algorithm.
Dynamic Programming
Idea: Turn recursion upside down.
Example: Floyd-Warshall algorithm for the all pairs shortest path
problem.
Algorithm Rec-Fib(n)
1. if n = 0 then
2. return 0
3. else if n = 1 then
4. return 1
5. else
6. return Rec-Fib(n − 1)+Rec-Fib(n − 2)
Ridiculously slow: exponentially many repeated computations of Rec-Fib(j)
for small values of j.
ADS: lects 12 and 13 – slide 3 –
Fibonacci Example (cont’d)
Why is the recursive solution so slow?
Running time T (n) satisfies
Fn
Fn−1 Fn−2
Algorithm Dyn-Fib(n)
1. F [0] = 0
2. F [1] = 1
3. for i ← 2 to n do
4. F [i] ← F [i − 1] + F [i − 2]
5. return F [n]
Build “from the bottom up”
Running Time
Θ(n)
Very fast in practice - just need an array (of linear size) to store the F(i)
values.
Further improvement to use Θ(1) space (but still Θ(n) time): Just use
variables to store the current and two previous Fi .
ADS: lects 12 and 13 – slide 6 –
Multiplying Sequences of Matrices
Recall
Multiplying a (p × q) matrix with a (q × r ) matrix (in the
standard way) requires
pqr
multiplications.
We want to compute products of the form
A1 · A2 · · · An .
30 · 1 · 40 + 40 · 10 · 25 + 30 · 40 · 25 = 41, 200
multiplications.
Multiplication order A · ((B · C ) · D) requires
1 · 40 · 10 + 1 · 10 · 25 + 30 · 1 · 25 = 1, 400
multiplications.
A1 · A2 · A3
3 × 100 100 × 2 2×2
X
n−1
T (n) = T (k) + T (n − k) + Θ(n).
k=1
This implies
T (n) = Ω(2n ).
Moreover,
1. n ← p.length − 1
2. for i ← 1 to n do
3. m[i, i] ← 0
4. for ` ← 2 to n do
5. for i ← 1 to n − ` + 1 do
6. j ←i +`−1
7. m[i, j] ← ∞
8. for k ← i to j − 1 do
9. q ← m[i, k] + m[k + 1, j] + pi−1 pk pj
10. if q < m[i, j] then
11. m[i, j] ← q
12. s[i, j] ← k
13. return s
Running Time: Θ(n3 )
ADS: lects 12 and 13 – slide 14 –
Example
A1 · A2 · A3 · A4
30 × 1 1 × 40 40 × 10 10 × 25
Solution for m and s
m 1 2 3 4 s 1 2 3 4
1 0 1200 700 1400 1 1 1 1
2 0 400 650 2 2 3
3 0 10 000 3 3
4 0 4
Optimal Parenthesisation
A1 · ((A2 · A3 ) · A4 ))
Algorithm Matrix-Chain-Multiply(A, p)
1. n ← A.length
2. s ←Matrix-Chain-Order(p)
3. return Rec-Mult(A, s, 1, n)
Algorithm Rec-Mult(A, s, i, j)
1. if i < j then
2. C ←Rec-Mult(A, s, i, s[i, j])
3. D ←Rec-Mult(A, s, s[i, j] + 1, j)
4. return (C ) · (D)
5. else
6. return Ai