//
//带括号矩阵连乘的模拟
//使用stack来解决
#include<iostream>
#include<stack>
#include<string>
using namespace std;
struct matrx
{
int row;
int col;
}ma[30];
char str[100000];
int main()
{
int n;
char ch;
cin>>n;
while(n--)
{
cin>>ch;
cin>>ma[ch-'A'].row>>ma[ch-'A'].col;
}
while(cin>>str)
{
int i;
int len,sum=0;
matrx temp1,temp2;
bool flags=1;
if(str[0]!='(')
{
cout<<0<<endl;
continue;
}
len=strlen(str);
stack<matrx> set;
for(i=1;i<len;i++)
{
if(str[i]=='(') ;
else if(str[i]==')')
{
//留意到这里,这样使用也行,之前用指针就不行
temp2.row=set.top().row;
temp2.col=set.top().col;
set.pop();
temp1.row=set.top().row;
temp1.col=set.top().col;
set.pop();
if(temp1.col!=temp2.row)
{
flags=0;
break;
}
sum+=(temp1.row)*(temp1.col)*(temp2.col);
matrx p;
p.row=temp1.row;
p.col=temp2.col;
set.push(p);
}
else
{
matrx p;
p.row=ma[str[i]-'A'].row;
p.col=ma[str[i]-'A'].col;
set.push(p);
}
}
if(flags)
cout<<sum<<endl;
else
cout<<"error"<<endl;
}
return 0;
}