矩阵连乘 LRJ白书 p141 栈 解析表达式
#include<iostream> #include<cstdio> #include<cstring> #include<sstream> #include<algorithm> #include<queue> #include<vector> #include<cmath> #include<map> #include<stack> #include<set> #include<fstream> #include<memory> #include<string> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define MAXN 102 #define INF 1000000009 /* 利用栈解析表达式 */ struct Matrix { int a, b; Matrix(int _a = 0,int _b=0):a(_a),b(_b){} }m[26]; stack<Matrix> s; int main() { int n; scanf("%d", &n); string str; for (int i = 0; i < n; i++) { cin >> str; int k = str[0] - 'A'; cin >> m[k].a >> m[k].b; } string expr; while (cin >> expr) { int len = expr.length(); bool error = false; int ans = 0; for (int i = 0; i < len; i++) { if (isalpha(expr[i])) s.push(m[expr[i] - 'A']); else if (expr[i] == ')') { Matrix m2 = s.top(); s.pop(); Matrix m1 = s.top(); s.pop(); if (m1.b != m2.a) { error = true; break; } ans += m1.a*m1.b*m2.b; s.push(Matrix(m1.a, m2.b)); } } if (error) cout << "error\n"; else cout << ans << endl; } }