/* stack 容器的应用:矩阵的表达式求值 A 矩阵是a * b,B 矩阵是b * c,则A * B 是a * c */ #include <cstdio> #include <iostream> #include <algorithm> #include <stack> #include <cmath> #include <cstring> #include <string> using namespace std; const int MAXN = 1e4 + 10; const int INF = 0x3f3f3f3f; struct Matrix { int a, b; Matrix (int a=0, int b=0) : a (a), b (b) {}; }m[26]; int main(void) //UVA 442 Matrix Chain Multiplication { //freopen ("UVA_446.in", "r", stdin); int n; string name; cin >> n; for (int i=1; i<=n; ++i) { cin >> name; int k = name[0] - ‘A‘; cin >> m[k].a >> m[k].b; } string expr; stack <Matrix> s; while (cin >> expr) { int len = expr.length (); bool error = false; int ans = 0; for (int i=0; i<len; ++i) { if (expr[i] >= ‘A‘ && expr[i] <= ‘Z‘) 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" << endl; else cout << ans << endl; } return 0; }
时间: 2024-10-09 13:59:16