TOJ 1135 Matrix Chain Multiplication

TOJ 1135 Matrix Chain Multiplication

很简单的题,给定N个矩阵,然后给出一系列运算式,用括号来限制运算,最后求一共进行了多少次乘法运算。
R(m,s) 和Q(s,n)相乘,要进行m*s*n次~
处理运算先后的时候,用栈实现,即后进先出就可以了。
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 Outout:
0
0
0
error
10000
error
3500
15000
40500
47500
15125
Code:
#include  < iostream >
#include 
< cstdio >
#include 
< string >
#include 
< map >
using   namespace  std;

struct  Matrx{
        
char  id;
        
int  x,y;
}a[
30 ];
Matrx stack[
100 ];
int  main()
{
        
int  i,j,k,n,ans;
        
bool  flag;
        map
< char , int > mark;
        scanf(
" %d " , & n);
        
for (i  =   1 ;i  <=  n; i ++ ){
                cin 
>>  a[i].id;
                scanf(
" %d%d " , & a[i].x, & a[i].y);
                mark[a[i].id] 
=  i;
        }
        
string  str;
        
while (cin >> str){
                ans 
=   0 ; flag  =   true ;
                
int  len  =  str.length();
                
int  head,tail;
                head 
=  tail  =   0 ;
                
for (i  =   0 ;i  < len; i ++ ){
                        
if (str[i]  ==   ' ( ' )
                                
continue ;
                        
else   if (str[i]  ==   ' ) ' ){      // pop
                                 if (head  ==   1 )
                                        head 
-- ;
                                
else   if (head  >   1 ){
                                        
int  tx  =  stack[head - 2 ].x;
                                        
int  ty  =  stack[head - 1 ].y;
                                        
if (stack[head - 2 ].y  !=  stack[head - 1 ].x) flag  =   false ;
                                        ans 
+=  stack[head - 2 ].x * stack[head - 2 ].y * stack[head - 1 ].y;
                                        head 
-=   2 ;
                                        stack[head].x 
=  tx;
                                        stack[head
++ ].y  =  ty;
                                }

                        }
                        
else {         //  push
                                stack[head ++ =  a[mark[str[i]]];

                        }
                }
                
if ( ! flag) printf( " error\n " );
                
else  printf( " %d\n " ,ans);
        }
}




你可能感兴趣的:(TOJ 1135 Matrix Chain Multiplication)