Chapter 10: 18, 24
Turn in: Implement a dynamic programming solution to the matrix
multiplication problem: Given a positive integer n <= 30 entered on the first
line of input, followed by n lines of input, where on the ith line is given the
dimensions of matrix Mi, find the optimal order in which to
perform the multiplication of M1*M2*...*Mn.
The output should be a fully parenthesized
version of the product and the total number of multiplications necessary to
multiply all of them together in that order. The input will be guaranteed to
be correct. That is, if Mi has r rows and c columns,
then Mi+1
has c rows (i.e., the multiplication is possible)
Example: If the input is
4 3 6 6 2 2 8 8 3Meaning there are 4 matrices, the first has 3 rows and 6 columns, .... The output will be:
(M1 * M2) * (M3 * M4) The optimal number of multiplications is 102Your solution should use dynamic programming (i.e., record answers to partial solutions in a table, rather than doing everything recursively). You will only receive 1/2 credit if you don't use dynamic programming. Good examples of dynamic programming can be found in sections 5.10, 6.8, and our solution of the all-pairs-shortest-paths (though we managed to optimize that by updating in place rather than keeping separate rows for each stage of the solution).
This problem will be graded separately from problem 18 above, will count for 30 points rather than 10, and cannot be used as one of the homework problems which can be dropped.
HintStart with the following algorithm, where m[i,j] contains the minimum number of multiplications to multiply Mi * ... * Mj. Note that m[i,i] = 0, and each time through the "l" loop, you move one step farther off the diagonal.
for i <- 1 to n do m[i,i] <- 0 for l <- 1 to n-1 do //l indicates how far off the diagonal for i <- 1 to n-l do j <- i+l m[i,j] <- Infinity for k <- i to j-1 do //See if optimal way of multiplying Mi to Mj //is by multiplying Mi to Mk,Mk+1 to Mj, // and then multiplying results together ...