#include <bits/stdc++.h>
using namespace std;
int n, m, k;
struct pro {
  string name;
  vector<string> type;
} f[1009];
map<string, string> Var;
bool isok(char c) { return isalpha(c) || isdigit(c); }
bool equal(pro &a, pro &b) {
  if (a.name != b.name) return false;
  if (a.type.size() != b.type.size()) return false;
  for (int i = 0; i < a.type.size(); i++)
    if (a.type[i] != "T" && a.type[i] != b.type[i]) return false;
  return true;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    string s;
    char c;
    cin >> s;
    while (!isok(c = getchar()))
      ;
    s = "";
    s.append(1, c);
    while (isok(c = getchar())) s.append(1, c);
    if (c != '(')
      while ((c = getchar()) != '(')
        ;
    f[i].name = s;
    while (1) {
      while (!isok(c = getchar()))
        ;
      s = "";
      s.append(1, c);
      while (isok(c = getchar())) s.append(1, c);
      f[i].type.push_back(s);
      if (c != ')' && c != ',')
        while ((c = getchar()) != ')' && c != ',')
          ;
      if (c == ')') break;
    }
  }
  scanf("%d", &m);
  for (int i = 0; i < m; i++) {
    string a, b;
    cin >> a >> b;
    Var[b] = a;
  }
  scanf("%d", &k);
  for (int i = 0; i < k; i++) {
    pro t;
    string s;
    char c;
    while (!isok(c = getchar()))
      ;
    s = "";
    s.append(1, c);
    while (isok(c = getchar())) s.append(1, c);
    if (c != '(')
      while ((c = getchar()) != '(')
        ;
    t.name = s;
    while (1) {
      while (!isok(c = getchar()))
        ;
      s = "";
      s.append(1, c);
      while (isok(c = getchar())) s.append(1, c);
      t.type.push_back(Var[s]);
      if (c != ')' && c != ',')
        while ((c = getchar()) != ')' && c != ',')
          ;
      if (c == ')') break;
    }
    int ans = 0;
    for (int j = 0; j < n; j++)
      if (equal(f[j], t)) ans++;
    cout << ans << endl;
  }
}
