uva442-矩阵链乘

Your job is to write a program that determines the number of elementary multiplications needed 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 (  ), representing the number of matrices in the first part. The next n lines each contain one capital letter, specifying the name 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 } 
Line       = Expression 
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 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.

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
这个题读懂题意其实还是挺简单的,不过我却做了一天,苦苦纠结于怎么来区分括号的优先级,后面看了提示知道用栈了,但还是纠结具体怎么区分,后面又看了遍别人解题报告,我才意识到自己在审题上想当然了,这里也算一个坑吧,题目中每个矩阵相乘就应该有一个括号,而不会存在(A*B*C)这样的情况,开始我一直在纠结这个,按题目的意思这种形式的正确表述是((A*B)*C),这样就方便太多了,不管左边括号,把字母压入栈,然后读到右边括号时把栈顶前两位算下一乘积又压入栈就好,这个题目就是考察栈的应用。
 
  
#include
#include
#include
#include
#include
#define LOCAL
using namespace std;

struct Node{
    int r;
    int c;
}node[30],node1[30];
int main(){
    #ifdef LOCAL
        freopen("input.txt","r",stdin);
        freopen("output.txt","w",stdout);
    #endif
    int n;
    char ch,s[100];
    scanf("%d",&n);
    getchar();
    for(int i=0;i m;
            int sum=0; 
            for(int i=0;i


你可能感兴趣的:(uvaoj)