#include <bits/stdc++.h>
using namespace std;
struct Matrix
{
int m;
int n;
void setM(int m,int n)
{
this->m=m;
this->n=n;
}
bool prok(Matrix & a)
{
return a.m==n;
}
int count_pro (Matrix & a)
{
return m*n*a.n;
}
Matrix& operator = (const Matrix p)
{
m=p.m;
n=p.n;
return *this;
}
};
stack <Matrix> op;
int main ()
{
int n;
cin>>n;
char x;
Matrix a[n];
for (int i=0;i<n;++i)
{
int m,n;
cin>>x>>m>>n;
a[i].setM(m,n);
}
string k;
while(cin>>k)
{
bool ok=true;
int sum=0;
for (int i=0;i<k.length();++i)
{
if (k[i]=='(')
{
continue;
}
else if ('A'<=k[i]&&k[i]<='Z')
{
op.push(a[k[i]-'A']);
}
else if (k[i]==')')
{
Matrix b=(Matrix)op.top();op.pop();
Matrix a=(Matrix)op.top();op.pop();
if (a.prok(b))
{
sum+=a.count_pro(b);
//cout<<"a b"<<a.m<<b.n<<endl;
Matrix c;
c.setM(a.m,b.n);
op.push(c);
}
else
{
ok=false;
break;
}
}
}
while (op.size()>1)
{
Matrix b=(Matrix)op.top();op.pop();
Matrix a=(Matrix)op.top();op.pop();
if (a.prok(b))
{
sum+=a.count_pro(b);
//cout<<"a b"<<a.m<<b.n<<endl;
Matrix c;
c.setM(a.m,b.n);
op.push(c);
}
else
{
ok=false;
break;
}
}
if (ok)
{
cout<<sum<<endl;
}
else
{
cout<<"error\n";
}
while(!op.empty())
{
op.pop();
}
}
}