We are given a sequence (chain) <A1,A2,A3,...,AN> of N matrices to be multiplied, and we wish to compute the product : A1A2A3...AN. We can evaluate the expression using the standard algorithm for multiplying pairs of matrices as a subroutine once we have paranthesized it to resolve all ambiguities in how the matrices are multiplied together. We will use the standard algorithm for multiplying matrices. If A is a p*q matrix and B is a q*r matrix, the resulting C is a p*r matrix, which requires p*q*r scalar multiplications.
A product of matrices is fully paranthesized if it is either a single matrix or the product of two fully paranthesized matrix products, surrounded by parantheses. Matrix multiplication is associative, and so all paranthesization yield the same product. But different paranthesization requires more scalar multiplication than the others.
Consider the problem of a chain <A1,A2,A3> of three matrices. Suppose that the dimensions of the matrices are 10*100, 100*5, and 5*50 respectively. If we multiply according to the paranthesization ((A1A2)A3), we perform 7500 scalar multiplications. If instead, we multiply according to the paranthesizaton (A1(A2A3)), we perform 75000 scalar multiplications. Thus, computing the product according to the first paranthesization is 10 times faster.
You are required to give the optimal paranthesization of a product that requires the minimal number of scalar multiplication.
Sample Input A Sample Input B 3 6 10 100 5 50 30 35 15 5 10 20 25 Sample Output A Sample Output B ((1*2)*3) ((1*(2*3))*((4*5)*6)) 7500 15125
![]() |
![]() |