Sample:
9
A 50 10
B 10 20
C 20 5
D 30 35
E 35 15
F 15 5
G 5 10
H 10 20
I 20 25
A
0
B
0
C
0
(AA)
error
(AB)
10000
(AC)
error
(A(BC))
3500
((AB)C)
15000
(((((DE)F)G)H)I)
40500
(D(E(F(G(HI)))))
47500
((D(EF))((GH)I))
15125
//矩阵链乘动态规划详解:https://blog.csdn.net/huzhigenlaohu/article/details/52182944
#include <cstdio>
#include <stack>
#include <iostream>
#include <string>
using namespace std;
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;
cin >> n;
for(int i = 0; i < n; i ++){
string name;
cin >> name;
int k = name[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) printf("error\n");
else printf("%d\n", ans);
}
return 0;
}