
def solve(exp)
  $error = false
  w, i = Molecule(exp, 0)
  w = "UNKNOWN" if $error
  w
end

def Molecule(exp, i)
  sum = 0
  while (i < exp.size) && (exp[i] != ")") do
    case exp[i]
    when /[A-Z]/
      w, i = Atom(exp, i)
      n = 1
      n, i = Number(exp, i) if exp[i] =~ /[0-9]/
      w *= n
    when "("
      i += 1
      w, i = Molecule(exp, i)
      i += 1
      n, i = Number(exp, i)
      w *= n
    end
    sum += w
  end
  [sum, i]
end

def Atom(exp, i)
  name = exp[i]
  i += 1
  if exp[i] =~ /[a-z]/
    name += exp[i]
    i += 1
  end
  unless $atom.key?(name)
    $error = true
    return [-1000, i]
  end
  [$atom[name], i]
end

def Number(exp, i)
  n = 0
  while(exp[i] =~ /[0-9]/)
    n *= 10
    n += exp[i].to_i
    i += 1
  end
  [n, i]
end

$atom = {}
while true do
  line = gets.chomp
  break if line == "END_OF_FIRST_PART"
  name, weight = line.split
  $atom.store(name, weight.to_i)
end
while true do
  line = gets.chomp
  break if line == "0"
  puts solve(line)
end