Matrix Chain Multiplication
Time limit1sMemory limit128 MB
Given matrices with dimensions and fully parenthesized products, report the elementary multiplication count or an error if dimensions mismatch.
- Level
Medium4 of 10
- Topics
- Stack, Recursion, Implementation
- Solved
- No attempts yet
Problem
Suppose you have to evaluate an expression like , where A, B, C, D and E are matrices.
Since matrix multiplication is associative, the order in which the multiplications are performed is arbitrary. However, the number of elementary multiplications needed depends strongly on the evaluation order you choose.
For example, let be a matrix, a matrix, and a matrix.
There are two different strategies to compute , namely and .
The first one takes 15000 elementary multiplications, but the second one only 3500.
Your job is to write a program that determines the number of elementary multiplications needed for a given evaluation strategy.
Input
The input consists of two parts: a list of matrices and a list of expressions.
The first line contains one integer (), the number of matrices. Each of the next lines contains one capital letter (the name of a matrix) and two integers (its number of rows and columns).
The second part strictly adheres to the following syntax, given in EBNF.
SecondPart = Line { Line } <EOF>
Line = Expression <CR>
Expression = Matrix | "(" Expression Expression ")"
Matrix = "A" | "B" | "C" | ... | "X" | "Y" | "Z"
Each line holds one expression, and expressions continue until the end of the file.
Output
For each expression in the second part of the input, print one line containing the word "error" if evaluation of the expression leads to an error due to non-matching matrices. Otherwise print one line containing the number of elementary multiplications needed to evaluate the expression in the way specified by the parentheses.