Matrix Chain Multiplication(栈的简单应用)
Matrix multiplication problem is a typical example of dynamical programming.
Suppose you have to evaluate an expression like A*B*C*D*E where A,B,C,D and E arematrices. Since matrix multiplication is associative, the order in which multiplications areperformed is arbitrary. However, the number of elementary multiplications neededstrongly depends on the evaluation order you choose.
For example, let A be a 50*10 matrix, B a 10*20 matrix and C a 20*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 3500.
Your job is to write a program that determines the number of elementary multiplicationsneeded for a given evaluation strategy.
Input Specification
Input consists of two parts: a list of matrices and a list of expressions.The first line of the input file contains one integer n (1 <= n <= 26),representing the number of matrices in the first part.The next n lines each contain one capital letter, specifying thename of the matrix, and two integers, specifying the number of rows and columns of the matrix.
The second part of the input file 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"
Output Specification
For each expression found in the second part of the input file, print one line containingthe 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.Sample Input
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 I 20 25 A B C (AA) (AB) (AC) (A(BC)) ((AB)C) (((((DE)F)G)H)I) (D(E(F(G(HI))))) ((D(EF))((GH)I))
Sample Output
0 0 0 error 10000 error 3500 15000 40500 47500 15125
Source: University of Ulm Local Contest 1996
AC Code:
1 #include <iostream> 2 #include <string> 3 #include <cstdio> 4 #include <stack> 5 6 using namespace std; 7 8 struct M 9 { 10 int col, row; 11 }m[27]; //矩阵数组 12 13 int main() 14 { 15 stack<M> S; 16 int n, cnt; //cnt为基本乘法执行的次数 17 char c; 18 string e; //算式 19 string::iterator it; 20 while(cin >> n) 21 { 22 cnt = 0; 23 while(n--) 24 { 25 cin >> c; //输入矩阵名称 26 cin >> m[c - 'A'].row >> m[c - 'A'].col; //输入矩阵的行数和列数 27 } 28 while(cin >> e) //输入算式 29 { 30 cnt = 0; 31 for(it = e.begin(); it != e.end(); it++) 32 { 33 if(*it == ')') 34 { 35 M a = S.top(); //获得左边的矩阵 36 S.pop(); 37 M b = S.top(); //获得右边的矩阵 38 S.pop(); 39 if(b.col != a.row) break; 40 cnt += (b.col * b.row * a.col); 41 b.col = a.col; 42 S.push(b); 43 } 44 else if(*it != '(') 45 { 46 S.push(m[*it - 'A']); 47 } 48 } 49 if(it != e.end()) puts("error"); 50 else cout << cnt << endl; 51 } 52 } 53 return 0; 54 }