--------------------------------------------------------------------------- COMP 731 - Data Struc & Algorithms - Lecture 23 - Tuesday, August 29, 2000 --------------------------------------------------------------------------- Today: Dynamic Programming, continued o Multiplying a sequence of matrices Multiplying a sequence of matrices ----------------------------------- Given: A sequence of matrices, A_1, ..., A_N where A_i is an d_{i-1} x d_i matrix. Example 5x3 3x9 9x2 2x10 10x6 /dimensions, in thousands. so N=5 d[0..5] = 5 3 9 2 10 6 Find: The cheapest way to multiply them together. Work out an example of two different ways to group the numbers. Think recursively! Let A[i,k] = the cost, in multiplies, of the cheapest way to group A_i ... A_k, where 1<=i<=k<=N Suppose you break up like (A_i ... A_j) (A_{j+1} ... A_k) This is This is d_{i-1} x d_j d_j x d_k Cost is A[i,j] + A[j+1,k] + d_{i-1} d_j d_k So: A[i,k] = min { A[i,j] + A[j+1,k] + d_{i-1} d_j d_k } j in {i, ..., k} Doing the base case more carefully: / 0 if i = k | | d_{i-1} d_j d_k if i = k-1 // not really necessary A[i,k] = | | min { A[i,j] + A[j+1,k] + d_{i-1} d_j d_k } if i < k-1 \ j in {i, ..., k-1} Example, continued. Carefully fill in the entries into the following table, using the formula above: j = 1 2 3 4 5 5x3 3x9 9x2 2xA Ax6 --------------------- i=1 5x3 | 0 |135| 84|184|264|<- Goal --------------------- i=2 3x9 | 0 | 54|114|210| ----------------- A_1 A_2 A_3 A_4 A_5 i=3 9x2 | 0 |180|228| d_0 d_1 d_2 d_3 d_4 d_5 ------------- 5 3 9 2 10 6 i=4 2x10 | 0 |120| --------- i=5 10x6 | 0 | ----- Show how to record "where you came from" and use it to recover the solution; in this case, answer turns out to be (A_1 (A_2 A_3)) (A_4 A_5) Double check that this takes 264 multiplies. Time is Theta(N^3)