#include <bits/stdc++.h>
using namespace std;
struct Proc {
  string name;
  vector<string> type;
};
Proc conv(char *buf, bool voided) {
  vector<string> T;
  char *tok = strtok(buf, " ,()");
  while (tok) {
    T.push_back(string(tok));
    tok = strtok(0, " ,()");
  }
  if (voided) T.erase(T.begin());
  Proc ans;
  ans.name = T[0];
  for (int(i) = (int)(1); (i) < (int)(T.size()); ++(i))
    ans.type.push_back(T[i]);
  return ans;
}
int main() {
  char skip[300];
  int n;
  cin >> n;
  cin.getline(skip, 300);
  vector<Proc> P(n);
  for (int(i) = (int)(0); (i) < (int)(n); ++(i)) {
    char buf[300];
    cin.getline(buf, 300);
    P[i] = conv(buf, true);
  }
  map<string, string> M;
  int m;
  cin >> m;
  cin.getline(skip, 300);
  for (int(i) = (int)(0); (i) < (int)(m); ++(i)) {
    string a, b;
    cin >> a >> b;
    M[b] = a;
  }
  int k;
  cin >> k;
  cin.getline(skip, 300);
  for (int(i) = (int)(0); (i) < (int)(k); ++(i)) {
    char buf[300];
    cin.getline(buf, 300);
    Proc now = conv(buf, false);
    for (int(i) = (int)(0); (i) < (int)(now.type.size()); ++(i))
      now.type[i] = M[now.type[i]];
    int ans = 0;
    for (int(i) = (int)(0); (i) < (int)(n); ++(i)) {
      if (P[i].name != now.name) continue;
      if (P[i].type.size() != now.type.size()) continue;
      bool flag = true;
      for (int(j) = (int)(0); (j) < (int)(P[i].type.size()); ++(j))
        if (P[i].type[j] != "T" && P[i].type[j] != now.type[j]) {
          flag = false;
          break;
        }
      if (!flag) continue;
      ++ans;
    }
    cout << ans << endl;
  }
  return 0;
}
