#include <bits/stdc++.h>
using namespace std;

string s;
int i;
map<string,int> chem;

int inner_morecule();
int number();
int atom();

int morecule(){
	int ret=0;
	while(s[i]!='$' && s[i]!=')'){
		int val=inner_morecule();
		if(val==-1) return -1;
		ret+=val;
	}
	return ret;
	
}

int inner_morecule(){
	int ret=0;
	if(s[i]=='('){
		i++;
		ret=morecule();
		i++;
	}else{
		ret=atom();
		if(ret==-1) return -1;
	}
	return ret*number();
}

int number(){
	int ret=0;
	while(isdigit(s[i])){
		ret=ret*10+s[i++]-'0';
	}
	return ret?ret:1;
}

int atom(){
	string ret=s.substr(i,1);
	i++;
	if(islower(s[i])){
		ret+=s[i];
		i++;
	}
	if(chem.find(ret)==chem.end()){
		return -1;
	}
	return chem[ret];
}

string solve(){
	int val=morecule();
	if(val==-1) return "UNKNOWN";
	return to_string(val);
}

int main(){
	{	string tmp;
		while(cin>>tmp,tmp!="END_OF_FIRST_PART"){
			int n; cin>>n;
			chem[tmp]=n;
		}
	}
	while(cin>>s,s!="0"){
		i=0;
		s+="$";
		cout<<solve()<<endl;
	}
	return 0;
}

