CS140-lecture-20211108

Matrix-chain multiplication #

image_2021-11-08-16-10-02 image_2021-11-08-16-12-52

  • total time complexity of \( \Theta(mnp) \)

image_2021-11-08-16-13-33 image_2021-11-08-16-36-31 image_2021-11-08-16-37-15 image_2021-11-08-16-42-27 image_2021-11-08-16-45-45

Optimal parenthesization #

image_2021-11-08-16-47-36 image_2021-11-08-16-53-19 image_2021-11-08-16-54-29 image_2021-11-08-16-54-54 image_2021-11-08-16-55-03 image_2021-11-08-16-58-15

  • this results in exponential complexity

So let’s use dynamic programming:

image_2021-11-08-17-06-54 image_2021-11-08-17-09-44

  • make sure to start with the base case, when i = j, the main diagonal of the array

image_2021-11-08-17-12-21

  • then, we can start to fill in the spaces to the top right of each base case.
  • note that the bottom left diagonal of the array will not be used, because i > j

image_2021-11-08-17-13-34 image_2021-11-08-17-17-39 image_2021-11-10-11-09-23 image_2021-11-10-11-10-38 image_2021-11-10-11-11-14 image_2021-11-10-11-11-28 image_2021-11-10-11-13-33 image_2021-11-10-11-15-19 image_2021-11-10-11-15-33

  • start with the base cases
  • loop over rows and columns
  • solve sub problems in each level

So how do we find the optimal solution once we’ve filled in the entire matrix? We can store the \( k \) value that gives the min value (this is the last line of the pseudo above).

image_2021-11-10-11-21-14 image_2021-11-10-11-22-00 image_2021-11-10-11-24-04 image_2021-11-10-11-24-09 image_2021-11-10-12-27-11

My solution in Python

Output

       0    50000     7500 
      -1        0     5000 
      -1       -1        0 

      -1        0        0 
      -1       -1        1 
      -1       -1       -1 

( A0 ( A1  A2 ))
7500 multiplications needed

       0     6000    25000    90000    86000    86000    99200 
      -1        0    10000    60000    80000    82400    87200 
      -1       -1        0   100000   120000    96000   105600 
      -1       -1       -1        0   100000    84000   108000 
      -1       -1       -1       -1        0    24000    72000 
      -1       -1       -1       -1       -1        0     9600 
      -1       -1       -1       -1       -1       -1        0 

      -1        0        0        0        0        0        0 
      -1       -1        1        2        3        4        5 
      -1       -1       -1        2        2        2        5 
      -1       -1       -1       -1        3        3        5 
      -1       -1       -1       -1       -1        4        5 
      -1       -1       -1       -1       -1       -1        5 
      -1       -1       -1       -1       -1       -1       -1 

( A0 ((((( A1  A2 ) A3 ) A4 ) A5 ) A6 ))
99200 multiplications needed