uva 442
- 运算顺序不是很清晰,但是用栈来处理,就变得明了
- 核心步骤是,把矩阵按运算顺序压入栈中,如果遇到
)
就从栈中取出两个运算,将结果压回,这样就集成了括号带来的运算顺序。
#include <iostream>
#include <map>
#include <stack>
#include <fstream>
#include <string>
#define TEST 0
using namespace std;
typedef pair<int, int> Matrix;
int cnt;
bool compute(Matrix &, Matrix &, Matrix &);
int main()
{
ofstream ofs;
if (TEST)
{
ofs.open("/home/lixiaoqi/Documents/Code/C++/1.txt");
if (!ofs.is_open())
throw runtime_error("FILE NOT OPEN!");
}
ostream &os = TEST ? ofs : cout;
char c;
bool OK;
int N, a, b;
Matrix matrix[26];
stack<Matrix> s;
cin >> N;
while (N--)
{
getchar();
c = getchar();
cin >> a >> b;
matrix[c - 'A'] = make_pair(a, b);
}
getchar();
while (cin >> c)
{
cnt = 0;
OK = true;
while ((c = getchar()) != '\n')
{
if (!OK)
continue;
if (c == ')')
{
Matrix B = s.top();
s.pop();
Matrix A = s.top();
s.pop();
Matrix _new;
OK = compute(A, B, _new);
if (OK)
s.push(_new);
}
else if (isalpha(c))
s.push(matrix[c - 'A']);
}
os << (OK ? to_string(cnt) : "error") << '\n';
}
return 0;
}
bool compute(Matrix &a, Matrix &b, Matrix &ret)
{
if (a.second != b.first)
return false;
cnt += a.first * a.second * b.second;
ret.first = a.first;
ret.second = b.second;
return true;
}