### subroutines

def bsearch(ranges, tm)
  i = 0
  j = ranges.length - 1

  while i <= j
    k = (i + j) / 2
    r0, r1 = ranges[k]
    if tm + 30 > r0 && tm < r1
      return k
    end

    if tm >= r1
      i = k + 1
    else
      j = k - 1
    end
  end

  nil
end

### main

loop do
  n = gets.to_i
  break if n == 0

  prgs = 7.times.map{[]}
  prghash = {}

  n.times do
    name, wd, st = gets.strip.split
    wdi = wd.to_i
    sti = st.to_i
    tm = (sti / 100 - 6) * 60 + (sti % 100)

    prghash[name] = [wdi, tm]
    prgs[wdi] << tm
  end
  #p prgs
  #p prghash

  for prg in prgs
    prg.sort!.uniq!
  end
  #p prgs

  pn = gets.to_i
  anchors = 7.times.map{[]}

  pn.times do
    wdi, sti = prghash[gets.strip]
    anchors[wdi] << sti
  end
  #p anchors

  count = 0

  for anc in anchors
    anc.sort!

    for i in (0...(anc.length - 1))
      if anc[i + 1] - anc[i] < 30
        count = -1
        break
      end
    end
    break if count == -1
  end

  if count == -1
    puts -1
    next
  end

  for i in (0..6)
    prg = prgs[i]
    anc = anchors[i]
    #p [prg, anc]

    ranges = [[0, 24 * 60]]
    for an in anc
      k = bsearch(ranges, an)
      if ! k.nil?
        r0, r1 = ranges[k]
        rs = []
        if r0 < an && an - r0 >= 30
          rs << [r0, an]
        end
        if an + 30 < r1 && r1 - an >= 60
          rs << [an + 30, r1]
        end
        ranges[k, 1] = rs
      end
    end
    count += anc.length

    for range in ranges
      r0, r1 = range

      for tm in prg
        break if tm + 30 > r1
        if tm >= r0
          #p [r0, r1, tm]
          count += 1
          r0 = tm + 30
        end
      end
    end
    #p ranges
  end

  puts count
end