Matrix Chain Multiplication UVa442

Times: 23 mins 栈在表达式计算的应用,参考数据结构课程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <stack>
#include <string>
#include <utility>
#define p pair<int, int>
using namespace std;
p x[30];
long long solve(string& exp)
{
stack<p> cal;
long long tot = 0, sum = 0;
if (exp.length() == 1)
return 0;
while (tot < exp.length())
{
if (exp[tot] == ')')
{
p x2 = cal.top(); cal.pop();
p x1 = cal.top(); cal.pop();
if (x1.second != x2.first)
return -1;
else
sum += x1.first * x1.second * x2.second;
cal.push(make_pair(x1.first, x2.second));
}
else if (exp[tot] != '(')
cal.push(x[exp[tot] - 'A']);
tot++;
}
return sum;
}
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
char xx;
int r, c;
cin >> xx >> r >> c;
x[xx - 'A'] = make_pair(r, c);
}
string exp;
while (cin >> exp)
{
long long res = solve(exp);
if (res != -1)
cout << res;
else
cout << "error";
cout << endl;
}
return 0;
}