#include<bits/stdc++.h>
using namespace std;

struct hoge{
    string name;
    int start;
    hoge(string name, int start) : name(name), start(start){ }
};
bool operator < (const hoge &a, const hoge &b){
    return a.start < b.start;
}

int main(void){
    while(true){
        int n;
        cin >> n;
        if(n==0) break;
        vector<hoge> v;
        for(int i=0; i<n; i++){
            string name;
            int start, weekday, s;
            cin >> name >> weekday >> start;
            s=weekday*24*60+start/100*60+start%100;
            v.push_back(hoge(name, s));
        }
        sort(v.begin(), v.end());
        int p;
        cin >> p;
        bool timezone[12000], tf=true;
        fill(timezone, timezone+12000, false);
        
        for(int i=0; i<p; i++){
            string str;
            cin >> str;
            for(int j=0; j<n; j++){
                if(tf){
                    if(v[j].name==str){
                        if(!timezone[v[j].start] && !timezone[v[j].start+29]){
                            for(int t=v[j].start; t<v[j].start+30; t++){
                                timezone[t]=true;
                            }
                        }else{
                            tf=false;
                            break;
                        }
                    }
                }
            }
        }
        int count=p;
        if(! tf) cout << -1 << "\n";
        else{
            for(int i=0; i<n; i++){
                //cout << v[i].name << " time=" << v[i].start << "\n";
                if(! timezone[v[i].start] && !timezone[v[i].start+29]){
                    //cout << "OK=" << v[i].name << "\n";
                    for(int j=v[i].start; j<v[i].start+30; j++){
                        timezone[j]=true;
                    }
                    count++;
                }
            }
            cout << count << "\n";
        }
        
        
    }
    
    
    return 0;
}
