#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <utility>
#include <cctype>
using namespace std;

#define rep(i,n) for(int (i)=0; (i)<(int)(n); ++(i))
#define foreach(c,i) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();i++)

int N, P;
map<string,int> all[7];
map<string,int> weeks;
bool flag[7][3100];

int main() {
  while (cin>>N, N) {
    rep(i,7) all[i].clear();
    weeks.clear();
    {
      string name;
      int week, start;
      rep(i,N) {
        cin>>name>>week>>start;
        all[week].insert(make_pair(name,start/100*60+start%100));
        weeks.insert(make_pair(name,week));
      }
      cin>>P;
      memset(flag, false, sizeof flag);
      //vector<string> fav;
      set<string> fav;
      bool ok  = true;
      rep(i,P) {
        cin>>name;
        //fav.push_back(name);
        fav.insert(name);
        int week = weeks[name];
        int offset = all[week][name];
        if (flag[week][offset] || flag[week][offset+29]) { ok = false; }
        if (!ok) { continue; }
        for (int j = offset; j < offset+30; ++j) flag[week][j] = true;
      }
      if (!ok) { puts("-1"); continue; }

      //sort(fav.begin(), fav.end());
      rep(i,7) {
        set<int> s;
        foreach(all[i],itr) {
          // if(!binary_search(fav.begin(), fav.end(), itr->first)) {
          //   if (s.count(itr->second)) s.insert(itr->second);
          // }
          if (!fav.count(itr->first)) {
            s.insert(itr->second);
          }
        }
        //cout<<"["<<s.size()<<"]"<<endl;
        foreach(s,itr) {
          int v = *itr;
          //cout<<"("<<v<<")"<<endl;
          if (flag[i][v] || flag[i][v+29]) continue;
          for (int j = v; j < v+30; ++j) flag[i][j] = true;
        }
      }

      int ret = 0;
      rep(i,7) {
        for (int j = 0; j < 3000; ++j) {
          if (!flag[i][j]) continue;
          //cout << i << "," <<j << endl;
          ++ret;
          j += 29;
        }
      }
      cout << ret << endl;
    }
  }
  return 0;
}