module Tree
  # Node
  class Node
    attr_accessor :name, :cost, :children
    def initialize(name, cost, children = [])
      @name, @cost, @children = name, cost, children
    end
  end

  # Tree
  class Tree
    attr_accessor :nodes

    def initialize(data)
      @nodes = data.map do |name, meta|
        Node.new name, *meta
      end
    end

    def min_cost(name)
      node = @nodes.find do |item|
        item.name == name
      end
      if node.children.empty?
        return node.cost
      end
      children_cost = node.children.inject(0) do |children_cost, name|
        children_cost + min_cost(name)
      end
      [node.cost, children_cost].min
    end
  end
end

res = []

loop do
  items = {}

  n = gets.to_i
  break if n == 0

  n.times do
    name, cost = gets.split
    items[name] = *cost.to_i
  end

  m = gets.to_i

  m.times do
    o, k, *qs = gets.split
    items[o] << qs
  end

  tree = Tree::Tree.new items
  res << tree.min_cost(gets.chomp)
end

puts res