注解
1、栈的应用:如果读入的字符是字母,就push到栈中。如果是右括号,就从栈中取两个栈顶元素,然后看这两个元素是否能做矩阵乘法,如果不能就输出错误,如果能就把结果矩阵的行列值计算出来,再写回到栈中。
代码
#include <iostream>
#include <stack>
using namespace std;
struct Matrix{
int row;
int col;
};
int main() {
Matrix m[26];
int T;
scanf("%d", &T);
for(int i=0; i<T; i++){
char c;
int a, b;
cin>>c>>a>>b;
m[c-'A'].row = a;
m[c-'A'].col = b;
}
string s;
while(cin>>s){
int ans = 0;
stack<Matrix> st;
bool error = false;
int len = s.length();
for(int i=0; i<len; i++){
if(s.at(i)>='A' && s.at(i)<='Z'){
st.push(m[s.at(i)-'A']);
}
else if(s.at(i)==')'){
Matrix m1 = st.top();
st.pop();
Matrix m2 = st.top();
st.pop();
if(m1.row != m2.col){
error = true;
break;
}
else{
ans += m2.row * m2.col * m1.col;
Matrix tmp;
tmp.row = m2.row;
tmp.col = m1.col;
st.push(tmp);
}
}
}
if(error){
cout<<"error"<<endl;
}
else{
cout<<ans<<endl;
}
}
return 0;
}