#include <vector>
#include <iostream>
#include <utility>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <functional>
#include <cmath>
#include <iomanip>
#include <map>
#include <numeric>
#include <list>
#include <assert.h>
#include <math.h>
#include <valarray>
#include <stdio.h>
#include <algorithm>
#include <set>
#include <complex>
#include <list>

using namespace std;
typedef long long int LL;
typedef pair<long long int, long long int> pii;
typedef pair<double, double> pdd;

#define SORT(c) sort((c).begin(),(c).end())
#define BACKSORT(c) sort((c).begin(),(c).end(),std::greater<LL>())
#define FOR(i,a,b) for(LL i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

vector<vector<int>> atom(26, vector<int>(27, -1));


int shiki(string& s, int& i);
int genshiA(string& s, int& i);
int genshiP(string& s, int& i);
int genshi(string& s, int& i);
int number(string& s, int& i);


bool flag = true;
int start(string& s, int& i) {
	flag = true;
	int a = shiki(s, i);
	if (flag) {
		return a;
	}
	else {
		return -1;
	}
}

int shiki(string& s, int& i) {
	int sum = 0;
	while (s[i] != '?'&&s[i] != ')') {
		int a = genshiA(s, i);
		sum += a;
	}
	
	return sum;
}

int genshiA(string& s, int& i) {
	int a = genshiP(s, i);
	
	if (isdigit(s[i])) {
		int b = number(s, i);
		a = a*b;
	}
	return a;
}

int genshiP(string& s, int& i) {
	if (s[i] == '(') {
		i++;
		int a = shiki(s, i);
		i++;
		return a;
	}
	else {
		int a = genshi(s, i);
		return a;
	}
}

int genshi(string& s, int& i) {
	char atomA = s[i];
	i++;
	char atomB = 'a' - 1;
	if ('a' <= s[i] && s[i] <= 'z') {
		atomB = s[i];
		i++;
	}
	int a = atom[atomA - 'A'][atomB - 'a' + 1];
	if (a == -1) {
		flag = false;
		return 0;
	}
	else {
		return a;
	}
}

int number(string& s, int& i) {
	int a = s[i] - '0';
	i++;
	if (isdigit(s[i])) {
		a = a * 10 + (s[i] - '0');
		i++;
	}
	return a;
}

int main()
{

	while (true) {
		string ss;
		cin >> ss;
		if (ss.size() ==17) {
			break;
		}
		int num;
		cin >> num;
		if (ss.size() == 1) {
			atom[ss[0] - 'A'][0] =num;
		}
		else {
			atom[ss[0] - 'A'][ss[1] - 'a' + 1] = num;
		}
	}
	while (true) {
		string ss;

		cin >> ss;
		ss = ss + "??????";
		if (ss[0] == '0') { break; }
		int k = 0;
		int nyaan = start(ss,k);
		if (nyaan == -1) {
			cout << "UNKNOWN" << endl;
		}
		else {
			cout << nyaan << endl;
		}

	}

}