栈对于表达式求值的应用,遇到字母进栈,遇到右括号出栈两次运算后再进栈
思路见码
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
using namespace std;
#define LL long long
//const int maxn=;
struct matrix{
int le,ri;
}mat[30];
stack<matrix> s;
string str;
int main(){
//freopen("input.txt","r",stdin);
int n;
scanf("%d",&n);
getchar();
for(int i=0;i<n;i++){
char id;
int le,ri;
scanf("%c%d%d",&id,&le,&ri);
mat[id-'A'].le=le;
mat[id-'A'].ri=ri;
getchar();
}
while(cin>>str){
int ok=1,ans=0;
int len=str.length();
for(int i=0;i<len;i++){
if(isalpha(str[i])) s.push(mat[str[i]-'A']);
else if(str[i]==')'){
matrix tmp1=s.top();s.pop();
matrix tmp2=s.top();s.pop();
if(tmp1.le==tmp2.ri){
matrix tmp3;
tmp3.le=tmp2.le;tmp3.ri=tmp1.ri;
s.push(tmp3);
ans+=tmp1.ri*tmp1.le*tmp2.le;
}
else{
ok=0;
break;
}
}
}
if(ok) printf("%d\n",ans);
else printf("error\n");
}
return 0;
}