题目链接:https://vjudge.net/problem/UVA-442
紫书代码:
1 #include<cstdio> 2 #include<string> 3 #include<algorithm> 4 #include<iostream> 5 #include<stack> 6 using namespace std; 7 8 struct Matrix 9 { 10 int a,b; 11 Matrix(int a=0,int b=0):a(a),b(b) {} 12 }m[26]; 13 14 stack<Matrix> s; 15 16 int main() 17 { 18 int n; 19 cin>>n; 20 for(int i=0;i<n;i++) 21 { 22 string name; 23 cin>>name; 24 int k=name[0]-'A'; 25 cin>>m[k].a>>m[k].b; 26 } 27 string expr; 28 while(cin>>expr) 29 { 30 int len=expr.length(); 31 bool error=false; 32 int ans=0; 33 for(int i=0;i<len;i++) 34 { 35 if(isalpha(expr[i]))s.push(m[expr[i]-'A']); 36 else if(expr[i]==')') 37 { 38 Matrix m2=s.top();s.pop(); 39 Matrix m1=s.top();s.pop(); 40 if(m1.b!=m2.a){error=true;break;} 41 ans+=m1.a*m1.b*m2.b; 42 s.push(Matrix(m1.a,m2.b)); 43 } 44 } 45 if(error)printf("error "); 46 else printf("%d ",ans); 47 } 48 return 0; 49 }