Professional Documents
Culture Documents
Matrix Chain-Products
Matrix Chain-Product:
Compute A=A0*A1*…*An-1
Dynamic Programming
Ai is di × di+1
Problem: How to parenthesize?
Example
B is 3 × 100
C is 100 × 5
D is 5 × 5
(B*C)*D takes 1500 + 75 = 1575 ops
B*(C*D) takes 1500 + 2500 = 4000 ops
C = A*B C is 10 × 5
A is d × e and B is e × f D is 5 × 10
e
f
Dynamic Programming 3 Dynamic Programming 6
1
Dynamic Programming 2/24/2005 1:46 AM
Dynamic Programming
Another Greedy Approach Algorithm Visualization
Idea #2: repeatedly select the product that uses The bottom-up N i , j = min{N i ,k + N k +1, j + d i d k +1d j +1}
the fewest operations. construction fills in the i ≤k < j
N array by diagonals
Counter-example: Ni,j gets values from
N 0 1 2 i j … n-1
Dynamic Programming
“Recursive” Approach Algorithm
Define subproblems: Since Algorithm matrixChain(S):
subproblems
Find the best parenthesization of Ai*Ai+1*…*Aj. overlap, we don’t Input: sequence S of n matrices to be multiplied
Let Ni,j denote the number of operations done by this use recursion. Output: number of operations in an optimal
subproblem. Instead, we parenthesization of S
The optimal solution for the whole problem is N0,n-1. construct optimal for i ← 1 to n − 1 do
subproblems
Subproblem optimality: The optimal solution can be “bottom-up.” Ni,i ← 0
defined in terms of optimal subproblems Ni,i’s are easy, so for b ← 1 to n − 1 do
There has to be a final multiplication (root of the expression start with them { b = j − i is the length of the problem }
tree) for the optimal solution. Then do for i ← 0 to n − b − 1 do
problems of
Say, the final multiply is at index i: (A0*…*Ai)*(Ai+1*…*An-1). “length” 2,3,… j←i+b
Then the optimal solution N0,n-1 is the sum of two optimal subproblems, Ni,j ← +∞
subproblems, N0,i and Ni+1,n-1 plus the time for the last multiply. and so on. for k ← i to j − 1 do
If the global optimum did not have these optimal Running time:
O(n3) Ni,j ← min{Ni,j, Ni,k + Nk+1,j + di dk+1 dj+1}
subproblems, we could define an even better “optimal”
return N0,n−1
solution.
Dynamic Programming 8 Dynamic Programming 11
2
Dynamic Programming 2/24/2005 1:46 AM
the best subset of Sk-1 with weight at most w or
the best subset of Sk-1 with weight at most w−wk plus item k
Dynamic Programming 15