Woburn ECOO 1997

Matrix Chain Multiplication

INPUT FILE: matrix.in
OUTPUT FILE: matrix.out

Suppose you have to evaluate an expression like A*B*C*D*E where A, B, C, D and E are matrices. Since matrix multiplication is associative, the order in which multiplications are performed is arbitrary. However, the number of elementary multiplications needed strongly depends on the evaluation order you choose. To multiply an x-by-y matrix by a y-by-z matrix (remember the # of columns in the first has to be the same as the # of rows in the second) takes x*y*z elementary operations.
For example, let A be a 50-by-10 matrix, B a 10-by-20 matrix and C a 20-by-5 matrix. There are two different strategies to compute A*B*C, namely (A*B)*C and A*(B*C). The first one takes 15000 elementary multiplications, but the second one only takes 3500.

Your job is to write the program that determines the number of elementary multiplications needed for a given evaluation strategy.

INPUT
Input consists of two parts: a list of matrices and a list of expressions. The first line of the input file contains one positive integer n < 26, representing the number of matrices in the first part. The next n lines each contain one capital letter giving the name of a matrix to speicified, followed by two integers specifying its dimensions.
The second part of the input file consists of a list of matrix expressions adhering to the following syntax:

Expression = Matrix | "(" Expression Expression ")"
Matrix = "A" | "B" | "C" | "D" | ... | "Y" | "Z"
The list of expressions will be terminated by a line containing only "*".

OUTPUT
For each expression found in the second part of the input file, print one line containing the number of elementary operations needed to evaluate the given expression; if evaluation leads to an error due to an attempt to multiply matrices whose sizes do not match (i.e. columns of the 1st not equal to rows of the 2nd) output the word "error".

Sample Input File

9
A 50 10
B 10 20
C 20 5
D 30 35
E 35 15
F 15 5
G 5 10
H 10 20
X 20 25
A
B
C
(AA)
(AB)
(AC)
(A(BC))
((AB)C)
(((((DE)F)G)H)X)
(D(E(F(G(HX)))))
((D(EF))((GH)X))
*

Output for Sample Input

0
0
0
error
10000
error
3500
15000
40500
47500
15125
Downloader failed! Response object 006~ASP 0159~Buffering Off~Buffering must be on.