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.
SecondPart = Line { Line } <EOF> Line = Expression <CR> Expression = Matrix | "(" Expression Expression ")" Matrix = "A" | "B" | "C" | ... | "X" | "Y" | "Z"
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))
0 0 0 error 10000 error 3500 15000 40500 47500 15125Source: University of Ulm Local Contest 1996
#include <iostream> #include <string> #include <cstdio> #include <stack> using namespace std; struct M { int col, row; }m[27]; //矩阵数组 int main() { stack<M> S; int n, cnt; //cnt为基本乘法执行的次数 char c; string e; //算式 string::iterator it; while(cin >> n) { cnt = 0; while(n--) { cin >> c; //输入矩阵名称 cin >> m[c - 'A'].row >> m[c - 'A'].col; //输入矩阵的行数和列数 } while(cin >> e) //输入算式 { cnt = 0; for(it = e.begin(); it != e.end(); it++) { if(*it == ')') { M a = S.top(); //获得左边的矩阵 S.pop(); M b = S.top(); //获得右边的矩阵 S.pop(); if(b.col != a.row) break; cnt += (b.col * b.row * a.col); b.col = a.col; S.push(b); } else if(*it != '(') { S.push(m[*it - 'A']); } } if(it != e.end()) puts("error"); else cout << cnt << endl; } } return 0; }