Matrix Chain Multiplication(栈的简单应用)

来源:互联网 发布:剑与魔法翅膀升阶数据 编辑:程序博客网 时间:2024/06/03 15:01
Matrix Chain Multiplication

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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 nextn 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

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

Sample Output

000error10000error350015000405004750015125

Source: University of Ulm Local Contest 1996
Submit   Status

elementary multiplication是指普通的乘法,比如1*2执行了一次elementary multiplication,1*2+6*9执行了两次elementary multiplication。矩阵相乘elementary multiplication次数的计算方法:设有50*10的矩阵A和10*20的矩阵B,显然成绩的结果是一个50*20的矩阵C,C中有50*20=1000个元素,每个元素是由A中一行10个元素和B中一列10个元素的乘积之和,执行elementary multiplication10次,故而供执行elementary multiplication1000 * 10次。设f(A,B)表示矩阵A和B相乘所需执行的elementary multiplication次数,有f(A, B) = A的列数 * AB的元素个数 = A的列数 * A的行数 * B的列数

AC Code:
#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;}