#!/usr/bin/ruby
#
# 1071.rb: BD Shelf
#

### main

loop do
  n, w = gets.split.map(&:to_i)
  break if (n | w) == 0

  animes = []
  n.times do
    stri, expi, pri = gets.strip.split
    animes << [stri, expi.to_i, pri.to_i]
  end
  #p animes

  qn = gets.to_i

  queries = qn.times.map{gets.strip}

  qmins = []

  for i in (0...qn)
    qi = queries[i]

    aoks = n.times.map{true}
    for j in (0...i)
      qj = queries[j]
      if qi.start_with?(qj) || qj.start_with?(qi)
        aoks[qmins[j]] = false
      end
    end

    ws = (w + 1).times.map{0}
    amins = (w + 1).times.map{nil}

    for j in (0...n)
      next if ! aoks[j]

      ajstr, ajexp, ajpri = animes[j]
      next if ! ajstr.include?(qi)

      pws = ws.clone
      pamins = amins.clone

      for k in (0..w)
        if ajpri <= k
          wsj = pws[k - ajpri] + ajexp
          if ws[k] < wsj
            ws[k] = wsj
            aminj = pamins[k - ajpri]
            amins[k] = j if aminj.nil? || animes[aminj][1] > ajexp
          end
        end
      end
    end
    #p [ws[w], amins[w]]

    qmins[i] = amins[w]

    puts (ws[w] > 0 ? ws[w] : -1)
  end
end