#include <iostream>
#include <string>
#include <map>
using namespace std;
int Molecule();
int Cule();
string s;
int p,flag;
map<string,int> m;

int main(){
  while(1){
    cin>>s;
    if(s=="END_OF_FIRST_PART") break;
    cin>>p;
    m.insert(make_pair(s,p));
  }
  while(1){
    cin>>s;
    if(s=="0") break;
    s=s+'$';
    p=flag=0;
    int r=Molecule();
    if(flag) cout<<"UNKNOWN"<<endl;
    else cout<<r<<endl;
  }
  return 0;
}

int Molecule(){
  int r=Cule();
  while(('A'<=s[p]&&s[p]<='Z')||s[p]=='(') r+=Cule();
  return r;
}

int Cule(){
  if(s[p]=='('){
    p++;
    int r=Molecule();
    p++;
    int num=Cule();
    return r*num;
  }
  if('A'<=s[p]&&s[p]<='Z'){
    string str;
    str+=s[p];
    int num=1,res;
    p++;
    if('a'<=s[p]&&s[p]<='z') str+=s[p],p++;
    if('0'<=s[p]&&s[p]<='9') num=Cule();
    if(m.find(str)!=m.end()) res=m[str]*num;
    else flag=1,res=0;
    return res;
  }
  if('0'<=s[p]&&s[p]<='9'){
    int num=0;
    while('0'<=s[p]&&s[p]<='9') num=num*10+s[p]-'0',p++;
    return num;
  }
}