#include<iostream> #include<stack> #include<cctype> #include<map> #include<string> using namespace std; struct matrix { int x,y; }; int main() { int n; cin>>n; char ch; int i,x,y; matrix ma; map<int,matrix> m; for(i=0;i<n;i++) { cin>>ch; cin.ignore(); cin>>x; cin.ignore(); cin>>y; cin.ignore(); ma.x=x; ma.y=y; m.insert(make_pair(ch-'A',ma)); } string temp; int flag2=0; while(getline(cin,temp)) { if(temp.length()==1) cout<<0<<endl; else { stack<int> st; int j,sum=0,flag=1; for(j=0;j<temp.length();j++) { if(temp[j]=='(') st.push(30); else if(temp[j]!='('&&temp[j]!=')') st.push(temp[j]-'A'); else { int a,b; a=st.top(); st.pop(); b=st.top(); st.pop(); if(m[a].x!=m[b].y) { flag=0; break; } else { sum+=m[a].y*m[b].x*m[a].x; st.pop(); matrix temp_ma; temp_ma.x=m[b].x; temp_ma.y=m[a].y; st.push(flag2+100); m.insert(make_pair(flag2+100,temp_ma)); flag2++; } } } if(flag) cout<<sum<<endl; else cout<<"error"<<endl; } } return 0; }