class List
  def initialize
    @list = {}
  end

  def <<(arg)
    arg = arg.chomp.split(" ")
    if arg.size == 2
      @list[arg[0]] = arg[1].to_i
    else
      value = arg[2, arg[1].to_i].inject(0){|sum, item|sum + @list[item]}
      @list[arg[0]] = value if @list[arg[0]] > value
    end
  end

  def get(arg)
    return @list[arg.chomp]
  end
end
def main
  while (n = gets.to_i) != 0
    list = List.new
    n.times do
      list << gets
    end
    gets.to_i.times do
      list << gets
    end
    puts list.get(gets)
  end
end
main