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

int solve(string str, map<string, int> &atom){
    int p = 0;
    int ans = 0;
    while(str[p] != '.'){
        if(str[p]=='('){
            int depth = 1;
            p++;
            int s = p;
            for(; depth!=0; p++){
                if(str[p]=='(') depth++;
                if(str[p]==')') depth--;
            }
            int subans = solve(str.substr(s, p-s-1) +".", atom);
            if(subans == -1) return -1;
            int num = str[p] - '0';
            p++;
            if('0' <= str[p] && str[p] <= '9'){
                num = num*10 + str[p]-'0';
                p++;
            }
            ans += subans * num;
        }else{
            string name = "";
            name += str[p];
            p++;
            int subans;
            if('a' <= str[p] && str[p] <= 'z'){
                name += str[p];
                p++;
                if(atom.count(name)==0) return -1;
                subans = atom[name];
            }else{
                if(atom.count(name)==0) return -1;
                subans = atom[name];
            }
            int num=1;
            if('0' <= str[p] && str[p] <= '9'){
                num = str[p]-'0';
                p++;
                if('0' <= str[p] && str[p] <= '9'){
                    num = num*10 + str[p]-'0';
                    p++;
                }
            }
            ans += subans * num;
        }
    }
    return ans;
}

int main(){
    map<string, int> atom;
    while(1){
        string name;
        cin >> name;
        if(name == "END_OF_FIRST_PART") break;
        int weight;
        cin >> weight;
        atom[name] = weight;
    }

    while(1){
        string molecule;
        cin >> molecule;
        if(molecule == "0") break;
        int ans = solve(molecule +".", atom);
        if(ans == -1){
            cout << "UNKNOWN" << endl;
        }else{
            cout << ans << endl;
        }
    }
    return 0;
}

