您的位置:首页 > 其它

矩阵连乘 LRJ白书 p141 栈 解析表达式

2017-04-20 10:19 260 查看
#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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: