Dynamic Programming 2
Dynamic Programming 2
Dynamic programming 2
Summary
Dynamic programming applied to
◦ Matrix product problem
Matrix Product
◦ Multiplying together n rectangular matrices
M = M1· M2 ··· Mn where each Mi has ri-1 rows and ri columns
The naïve matrix multiplication algorithm takes pqr operations to multiply
a p x q matrix by a q x r matrix
we know matrix multiplication is associative so we can evaluate the
product in any order. However, some order are cheaper than others.
Objective here is to find the cost of cheapest one.
(Note: Matrix product is not commutative)
Matrix Product
Example
◦ If we multiply from right to left the following 4 matrices
10 x 20 20 x 50 50 x 1 1 x 100
20 x 1 cost = 1000
10 x 1 cost = 200
( M 1 M 2 M k ) ( M k 1 M n )
X ( k ) ways X ( n k ) ways
Therefore,
2
X (3) X (k ) X (3 k ) X (1) X (2) X (2) X (1) 2
k 1
n 1
X (n) X (k ) X (n k )
k 1
n 1
2 k 2 2 n k 2 (by induction hypothesis )
k 1
n 1
2 n 4 (n 1)2 n 4
k 1
2n2
Matrix Product
Divide and Conquer
Mi.Mi+1…..MJ
(Mi.Mi+1…Mk)(Mk+1…MJ).
function cost(i, j)
Hence, n 0
n 1
T ( n) 2 T ( m) dn
m 1
Divide and Conquer algorithm
Therefore,
n 1 n2
T ( n) T ( n 1) 2 T ( m) dn 2 T (m) d ( n 1)
m 1 m 1
2T ( n 1) d
T ( n) 3T ( n 1) d So,
T ( n) 3T ( n 1) d 3(3T ( n 2) d ) d
9T ( n 2) 3d d
9(3T ( n 3) d ) 3d d
27T ( n 3) 9d 3d d
m 1 n 1
3 T ( n m) d 3 .... 3 T (0) d 3l
m l n
l 0 l 0
3 n
1
c3n d (c d / 2)3n
2
Hence, T ( n) (3n )
Dynamic Programming
This is a job for
D
Dynamic Programming !!!
Otherwise.
When we fill in the table , we had better makes sure that m[i, k]
and m[k+1, j] are filled in before we compute m[i, j]. Compute
entries of m[] in increasing order of difference between
i j
parameters.
i
j
Details
r0 = 10 , r1 = 20, r2 = 50, r3 = 1, r4 = 100 .
= r0r1r2 = 10000
j := i + 1
m[i, j ] := …
Filling the second
superdiagonal
for i:= 1 to n – 2 do
j := i + 2
m[i, j] := …
Filling the dth superdiagonal
for i:= 1 to n – d do
j:= i + d
m[i , j] := …..
The algorithm
function matrix(n)
4. j := i + d
6. return (m[1,n])
Analysis
Line 1 costs of O(n)
Line 5 costs O(n) (can be done with a single for-loop)
Lines 4 and 6 costs O(1)
The for-loop on line 3-5 costs O(n2)
The for-loop on lines 2-5 costs O(n3).
Therefore, the algorithm runs in the time O(n3). This is a
characteristic of many dynamic programming algorithms.
Reading: Cormen(2nd Ed.)= 15.2,15.3
Other orders
Assignment #4 Due Date: 30.9.13
5 matrices
10 matrices
25 matrices