#include<iostream>
#include<stack>
#include<string>
#include<cctype>
using namespace std;
#define N 30
struct node
{
char m;
int r,c;
} a[N];
string s;
bool process(int& ans)
{
int len,i;
stack<node> sta;
node x,y,t;
len=s.length();
if(len==1)
{
ans=0;
return true;
}
ans=0;
for(i=0;i<len;i++)
if(isupper(s[i]))
sta.push(a[s[i]-'A']);
else if(s[i]==')')
{
x=sta.top();
sta.pop();
y=sta.top();
sta.pop();
if(x.r!=y.c) return false;
t.r=y.r;
t.c=x.c;
ans+=y.r*y.c*x.c;
sta.push(t);
}
return true;
}
int main()
{
int n,i,ans;
char c;
cin>>n;
for(i=0;i<n;i++)
{
getchar();
cin>>c;
a[c-'A'].m=c;
cin>>a[c-'A'].r>>a[c-'A'].c;
}
while(cin>>s)
{
if(!process(ans))
cout<<"error"<<endl;
else
cout<<ans<<endl;
}
return 0;
}