#include<iostream>
#include<string>
#include<map>
using namespace std;

map<string,int> idx;
int p;

int calc(string s){
	int res=0;
	while(p<s.size()){
		if(s[p]==')'){p++; break;}
		int weight=0;
		string f;
		if(isupper(s[p])){
			f+=s[p];p++;
			if(p<s.size() && islower(s[p])){
				f+=s[p]; p++;
			}
			if(!idx.count(f)) return -1;
			weight=idx[f];
		}
		else if(s[p]=='('){
			p++;
			weight=calc(s);
			if(weight<0) return -1;
		}
		int mul=0;
		while(p<s.size() && isdigit(s[p])){
			mul*=10;
			mul+=s[p]-'0';
			p++;
		}
		if(mul==0) mul=1;
		res+=weight*mul;
	}
	return res;
}

int main()
{
	string s;
	while(cin>>s){
		if(s.size()>=3) break;
		int w; cin>>w;
		idx[s]=w;
	}
	while(cin>>s){
		if(s=="0") break;
		p=0;
		int ans=calc(s);
		if(ans<0) cout<<"UNKNOWN"<<endl;
		else cout<<ans<<endl;
	}
	return 0;
}