代码:
#include <iostream>
#include <cstring>
using namespace std;
bool f;
int i, n, t[1000], ans, total, tt[1000];
char c, s[1000];
struct {
int x;
int y;
}v[1000];
void tmj(int n) {
int i, j, a1, a2, b1, b2;
memset(tt,0,sizeof(tt));
if (n > 3) {
for (i = 0; i < n - 3; i++) {
if (t[i] == -1&&t[i+3] == -2) {
a1 = v[t[i + 1]].x;
a2 = v[t[i + 1]].y;
b1 = v[t[i + 2]].x;
b2 = v[t[i + 2]].y;
if (a2 != b1) {
f = 0;
return ;
}
ans = ans + a1 * a2 * b2;
v[total].x = a1;
v[total].y = b2;
for (j = 0; j < i; j++) {
tt[j] = t[j];
}
tt[i] = total;
n = n - 3;
for (j = i + 1; j < n; j++) {
tt[j] = t[j + 3];
}
total++;
break;
}
}
for (i = 0; i < 1000; i++) t[i] = tt[i];
tmj(n);
}
}
int main() {
cin >> n;
for (i = 0; i < n; i++) {
cin >> c >> v[c-'A'].x >> v[c-'A'].y;
}
while (cin >> s) {
//Input
memset(t,0,sizeof(t));
f = 1;
ans = 0;
total = 100;
int l = strlen(s);
for (i = 0; i < l; i++)
if (s[i] == '(') {
t[i] = -1 ;
} else if (s[i] == ')') {
t[i] = -2 ;
} else t[i] = s[i] - 'A';
//Combine
tmj(strlen(s));
if (f)
cout << ans << endl;
else cout << "error" << endl;
}
return 0;
}