#include <bits/stdc++.h>
using namespace std;
char buf[2333];
char *p;
string s, ss, ty, name;
struct Node {
  string name;
  vector<vector<string> > ty;
};
vector<Node> fun;
vector<string> tv;
Node tn;
map<string, string> var;
void skip() {
  while (*p == ' ') p++;
}
string get_word() {
  string s = "";
  while (*p >= 'a' && *p <= 'z' || *p >= 'A' && *p <= 'Z' ||
         *p >= '0' && *p <= '9') {
    s += *p;
    *p++;
  }
  return s;
}
void gao() {
  p = buf;
  skip();
  get_word();
  skip();
  s = get_word();
  skip();
  tv.clear();
  p++;
  while (true) {
    skip();
    ss = get_word();
    tv.push_back(ss);
    skip();
    if (*p == ')') break;
    p++;
  }
  int flag = 0;
  for (int i = 0; i < fun.size(); i++) {
    if (s == fun[i].name) {
      flag = 1;
      fun[i].ty.push_back(tv);
      break;
    }
  }
  if (!flag) {
    tn.name = s;
    tn.ty.clear();
    tn.ty.push_back(tv);
    fun.push_back(tn);
  }
}
void ri() {
  p = buf;
  skip();
  s = get_word();
  tv.clear();
  skip();
  p++;
  while (true) {
    skip();
    ss = get_word();
    tv.push_back(ss);
    skip();
    if (*p == ')') break;
    p++;
  }
  int ans = 0;
  for (int i = 0; i < fun.size(); i++) {
    if (fun[i].name == s) {
      for (int j = 0; j < fun[i].ty.size(); j++) {
        if (tv.size() == fun[i].ty[j].size()) {
          int flag = 1;
          for (int k = 0; k < tv.size(); k++) {
            if (fun[i].ty[j][k] == "T" || fun[i].ty[j][k] == var[tv[k]])
              continue;
            else {
              flag = 0;
              break;
            }
          }
          if (flag) ans++;
        }
      }
    }
  }
  printf("%d\n", ans);
}
int n, m, q;
int main() {
  scanf("%d", &n);
  getchar();
  for (int i = 0; i < n; i++) {
    fgets(buf, sizeof(buf), stdin);
    gao();
  }
  scanf("%d", &m);
  string ty, name;
  for (int i = 0; i < m; i++) {
    cin >> ty >> name;
    var[name] = ty;
  }
  scanf("%d", &q);
  getchar();
  for (int i = 0; i < q; i++) {
    fgets(buf, sizeof(buf), stdin);
    ri();
  }
  return 0;
}
