题意:给出每个矩阵的行列,计算矩阵的表达式,如果错误输出error,否则输出答案
分析:表达式求值,stack 容器的应用:矩阵的表达式求值A 矩阵是a * b,B 矩阵是b * c,则A * B 是a * c。遇到')'弹出两个矩阵相乘,错误的话直接break
收获:以前做过了,现在会表达式求值后,这题也太容易了
代码:
/************************************************
* Author :Running_Time
* Created Time :2015-8-29 10:22:51
* File Name :UVA_442.cpp
************************************************/
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <cstdlib>
#include <ctime>
using namespace std;
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
typedef long long ll;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
struct Martrix {
int a, b;
Martrix (int _a = 0, int _b = 0) : a (_a), b (_b) {};
}m[26];
int main(void) {
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 exp;
stack<Martrix> S;
while (cin >> exp) {
bool error = false;
int ans = 0;
int len = exp.length ();
for (int i=0; i<len; ++i) {
if ('A' <= exp[i] && exp[i] <= 'Z') S.push (m[exp[i]-'A']);
else if (exp[i] == ')') {
Martrix m1 = S.top (); S.pop ();
Martrix m2 = S.top (); S.pop ();
if (m2.b != m1.a) {
error = true; break;
}
ans += m2.a * m2.b * m1.b;
S.push (Martrix (m2.a, m1.b));
}
}
if (error) cout << "error" << endl;
else cout << ans << endl;
}
return 0;
}