### subroutines

# <mol> := <atom> | <atom> <num> | '(' <mol> ')' <num> | <mol> <mol>
# <atom> := [A-Z] | [A-Z][a-z]
# <num> := [0-9]+

def mol(str)
  #p "mol"
  m = 0

  while str[$pos] && str[$pos] != ')'
    if str[$pos] >= 'A' && str[$pos] <= 'Z'
      a = atom(str)
      return nil if a.nil?
      if str[$pos] && str[$pos] >= '0' && str[$pos] <= '9'
        n = num(str)
        a *= n
      end
      m += a
    elsif str[$pos] == '('
      $pos += 1
      m0 = mol(str)
      return nil if m0.nil?
      $pos += 1
      n = num(str)
      m += m0 * n
    end
  end

  m
end

def atom(str)
  #p "atom"
  at = str[$pos]
  $pos += 1
  if str[$pos] && str[$pos] >= 'a' && str[$pos] <= 'z'
    at += str[$pos]
    $pos += 1
  end
  $atbl[at]
end

def num(str)
  #p "num"
  n = 0
  while str[$pos] && str[$pos] >= '0' && str[$pos] <= '9'
    n = n * 10 + str[$pos].to_i
    $pos += 1
  end
  n
end

### main

$atbl = {}
loop do
  line = gets.strip
  break if line == 'END_OF_FIRST_PART'

  ai, wi = line.split
  $atbl[ai] = wi.to_i
end
#p $atbl

loop do
  str = gets.strip
  break if str == '0'

  $pos = 0
  m = mol(str)
  puts (m || 'UNKNOWN')
end