open Scanf

module MarketPrice = Map.Make (
                   struct
                     type t = string
                     let compare (a : string) b = compare a b
                   end)

module Recipe = MarketPrice

let compute_cheapest_price product market_prices recipes =
  let memo = Hashtbl.create (MarketPrice.cardinal market_prices) in
  let rec compute product =
    try Hashtbl.find memo product
    with Not_found ->
      let cheapest_price =
        let market_price = MarketPrice.find product market_prices in
        if not (Recipe.mem product recipes) then market_price
        else
          List.fold_left
            (fun price material -> price + (compute material))
            0 (Recipe.find product recipes)
          |> min market_price in
      Hashtbl.add memo product cheapest_price;
      cheapest_price in
  compute product

let read_lines n =
  let rec read_lines n acc =
    if n = 0 then List.rev acc
    else read_lines (pred n) ((read_line ())::acc) in
  read_lines n []

let split_list = Str.split (Str.regexp " ")

let rec solve () =
  let n = int_of_string (read_line ()) in
  if n = 0 then ()
  else begin
    let market_prices =
      List.fold_left
        (fun market_prices line ->
         sscanf line "%s %d"
                (fun product price ->
                 MarketPrice.add product price market_prices))
        MarketPrice.empty
        (read_lines n) in
    let m = int_of_string (read_line ()) in
    let recipes =
      List.fold_left
        (fun recipes line ->
         let open List in
         let columns = split_list line in
         let product, materials = hd columns, tl (tl columns) in
         Recipe.add product materials recipes)
        Recipe.empty
        (read_lines m) in
    print_int (compute_cheapest_price (read_line ()) market_prices recipes);
    print_newline ();
    solve()
  end

let () = solve ()