//利用栈来解析表达式 //本题表达式比较简单,可以用一个栈来完成;遇到字母时入栈,遇到右括号时出栈并计算,然后结果入栈。因为输入保证合法,括号无须入栈 #include <iostream> #include <string> #include <stack> #include <cctype> using namespace std; struct Martrix { int a, b; Martrix(int a = 0, int b = 0):a(a), b(b) { } } m[26]; stack<Martrix>s; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { string name; cin >> name; int k = name[0] - 'A'; cin >> m[k].a >> m[k].b; } string expr; while (cin >> expr) { int len = expr.length(); int error = 0, ans = 0; for (int i = 0; i < len; i++) { char &tp = expr[i]; //tp is short for temp if (isalpha(tp)) s.push(m[tp - 'A']); else if (tp == ')') { Martrix m2 = s.top(); s.pop(); Martrix m1 = s.top(); s.pop(); if (m1.b != m2.a) { error = 1; break; } ans += m1.a * m1.b * m2.b; s.push(Martrix(m1.a, m2.b)); } } if (error) cout << "error" << endl; else cout << ans << endl; } return 0; }