#include <bits/stdc++.h>
using namespace std;
const int M = 1000 + 10;
const double eps = 1e-9;
struct FUN {
  string name;
  vector<string> variable;
} fun[M];
void skipspace(string s, int &id) {
  int slen = s.length();
  while (id < slen && s[id] == ' ') {
    id++;
  }
  return;
}
map<string, string> dic;
int main() {
  int n;
  cin >> n;
  string dummy;
  getline(cin, dummy);
  for (int i = 0; i < n; i++) {
    string s;
    getline(cin, s);
    int id = 0;
    int slen = s.length();
    skipspace(s, id);
    id = id + 4;
    skipspace(s, id);
    string t = "";
    while (id < slen &&
           ((s[id] >= 'a' && s[id] <= 'z') || (s[id] >= '0' && s[id] <= '9'))) {
      t = t + s[id];
      id++;
    }
    fun[i].name = t;
    skipspace(s, id);
    id++;
    string u = "";
    for (int j = id; j < slen; j++) {
      if (s[j] != ' ') {
        u = u + s[j];
      }
    }
    int ulen = u.length();
    id = 0;
    while (id < ulen) {
      int eid = id;
      string t = "";
      while (id < ulen && ((u[id] >= 'a' && u[id] <= 'z') ||
                           (u[id] >= '0' && u[id] <= '9') || u[id] == 'T')) {
        t = t + u[id];
        id++;
      }
      id++;
      fun[i].variable.push_back(t);
    }
  }
  int k;
  cin >> k;
  for (int i = 0; i < k; i++) {
    string s1, s2;
    cin >> s1 >> s2;
    dic[s2] = s1;
  }
  int m;
  cin >> m;
  getline(cin, dummy);
  for (int i = 0; i < m; i++) {
    string s;
    getline(cin, s);
    int slen = s.length();
    int id = 0;
    skipspace(s, id);
    string name = "";
    while (id < slen &&
           ((s[id] >= 'a' && s[id] <= 'z') || (s[id] >= '0' && s[id] <= '9'))) {
      name = name + s[id];
      id++;
    }
    vector<string> v;
    skipspace(s, id);
    id++;
    string u = "";
    for (int j = id; j < slen; j++) {
      if (s[j] != ' ') {
        u = u + s[j];
      }
    }
    int ulen = u.length();
    id = 0;
    while (id < ulen) {
      int eid = id;
      string t = "";
      while (id < ulen && ((u[id] >= 'a' && u[id] <= 'z') ||
                           (u[id] >= '0' && u[id] <= '9'))) {
        t = t + u[id];
        id++;
      }
      id++;
      v.push_back(t);
    }
    int cnt = 0;
    for (int j = 0; j < n; j++) {
      if (fun[j].name == name && fun[j].variable.size() == v.size()) {
        bool ok = true;
        set<string> va;
        for (int d = 0; d < v.size(); d++) {
          if (fun[j].variable[d] == "T") {
            va.insert(dic[v[d]]);
          } else {
            if (fun[j].variable[d] != dic[v[d]]) {
              ok = false;
              break;
            }
          }
        }
        if (ok) {
          cnt++;
        }
      }
    }
    cout << cnt << endl;
  }
  return 0;
}
