Matrix chain multiplication order
Time limit1sMemory limit256 MB
Find the parenthesization of N given matrices that minimizes the total number of scalar multiplications.
- Level
Medium4 of 10
- Topics
- Dynamic programming, Matrix
- Solved
- No attempts yet
Problem
Multiplying an matrix by an matrix takes scalar multiplications. When several matrices are multiplied, the total number of scalar multiplications depends on the order in which the products are taken.
Suppose is , is , and is . There are two orders for computing the product .
- Multiplying first and then multiplying by costs scalar multiplications for .
- Multiplying first and then multiplying on the left costs scalar multiplications for .
The resulting matrix is the same, but the count of operations changes with the order.
Given the sizes of matrices, write a program that finds the minimum number of scalar multiplications needed to multiply all of them. You must not reorder the matrices given in the input.
Input
The first line contains the number of matrices . ()
Each of the next lines contains the size and of one matrix, in the order the matrices are multiplied. ()
The input always describes sizes that can be multiplied in the given order. That is, the column count of the -th matrix equals the row count of the -th matrix.
Output
Print the minimum number of scalar multiplications needed to multiply all the given matrices. The answer is at most . Even the worst order takes at most operations.