def solve(depends, items, name)
  depend = depends[name]
  return items[name] if depend.nil?
  [depend.map {
     |dep_name| solve(depends, items, dep_name)
   }.reduce(&:+),
   items[name]].min
end
loop do
  items = {}
  n = gets.to_i
  break if n == 0
  n.times do 
    name, price = gets.split(" ")
    items[name] = price.to_i
  end
  depends = {}
  gets.to_i.times do
    v = gets.split(" ")
    depends[v[0]] = v[2..-1]
  end
  name = gets.strip
  puts solve(depends, items, name)
end