L24 DynamicProgramming I
L24 DynamicProgramming I
• Matrix compatibility:
C=AB C=A1 A2 Ai Ai+1 An
colA = rowB coli = rowi+1
rowC = rowA rowC = rowA1
colC = colB colC = colAn
MATRIX-MULTIPLY(A, B)
k cols[B]
j cols[B] j
i * k =i
rows[A] A C
rows[A]
MA512: Data Structures and Algorithms
8
Matrix-Chain Multiplication
• In what order should we multiply the matrices?
A1 A2 An
• Parenthesize the product to get the order in which
matrices are multiplied
• E.g.: A1 A2 A3 = ((A1 A2) A3)
= (A1 (A2 A3))
• Which one of these orderings should we choose?
The order in which we multiply the matrices has a
significant impact on the cost of evaluating the product
1 2 3 n
n
m[1, n] gives the optimal
solution to the problem
j
Compute rows from bottom to top 3
and from left to right 2
1
i
MA512: Data Structures and Algorithms
23
Example: Bottom-up Approach
• m[i,j] = min {m[i, k] + m[k+1, j] + pi-1pkpj}
m[2, 2] + m[3, 5] + p1p2p5 k=2
m[2, 5] = min m[2, 3] + m[4, 5] + p1p3p5 k=3
m[2, 4] + m[5, 5] + p1p4p5 k=4
1 2 3 4 5 6
6
Values m[i, j] depend only on values
5
that have been previously computed
4 Overlapping subproblems
3
j
2
1
i
MA512: Data Structures and Algorithms
24
Another example 1 2 3
Compute A1 A2 A3 3 2 7500 225000 0
• A1: 10 x 100 (p0 x p1)
1
• A2: 100 x 5 (p1 x p2) 2 5000 0
• A3: 5 x 50 (p2 x p3)
0
1
m[i, i] = 0 for i = 1, 2, 3
m[1, 2] = m[1, 1] + m[2, 2] + p0p1p2 (A1A2)
= 0 +0 + 10*100*5 = 5,000
m[2, 3] = m[2, 2] + m[3, 3] + p1p2p3 (A2A3)
= 0 + 0 + 100*5*50 = 25,000
m[1, 3] = min {m[1, 1] + m[2, 3] + p0p1p3 = 75,000 (A1(A2A3))
m[1, 2] + m[3, 3] + p0p2p3 = 7,500} ((A1A2)A3)
O(N3)
1 2 3 4 5 6
6 3 3 3 5 5 - • s[1, n] = 3 A1..6 = A1..3 A4..6
5 3 3 3 4 - • s[1, 3] = 1 A1..3 = A1..1 A2..3
4 3 3 3 - • s[4, 6] = 5 A4..6 = A4..5 A6..6
3 1 2 -
j
2 1 -
1 -
i
MA512: Data Structures and Algorithms
29
Algorithm: Print-Optimal-Parens()