#include <bits/stdc++.h>
using namespace std;
using INT = long long;
using VI = vector<int>;
using pii = pair<int, int>;
template <typename A, typename B>
void smin(A &a, const B &b) {
  if (a > b) a = b;
}
template <typename A, typename B>
void smax(A &a, const B &b) {
  if (a < b) a = b;
}
char s[1010], tmp[] = "( ,)", kk[10];
VI vec;
string ss;
vector<VI> ans = vector<VI>(5);
map<string, int> num;
void update() {
  gets(s);
  int nn = 0;
  vec.clear(), ss.clear();
  for (char *t = strtok(s, tmp); t; t = strtok(0, tmp)) {
    nn++;
    if (nn == 2) ss = t;
    if (nn > 2) {
      if (t[0] == 'T')
        vec.push_back(0);
      else if (t[0] == 'i')
        vec.push_back(1);
      else if (t[0] == 'd')
        vec.push_back(2);
      else
        vec.push_back(3);
    }
  }
  while (vec.size() < 5) vec.push_back(-1);
  for (int i = 0; i < 5; i++) ans[i].clear();
  for (int i = 0; i < 5; i++) {
    if (~vec[i]) {
      if (vec[i])
        ans[i].push_back(vec[i]);
      else
        ans[i].push_back(1), ans[i].push_back(2), ans[i].push_back(3);
    } else
      ans[i].push_back(-1);
  }
  ss += "$     ";
  int len = ss.size();
  for (int i0 = 0; i0 < ans[0].size(); i0++) {
    ss[len - 5] = 'A' + ans[0][i0];
    for (int i1 = 0; i1 < ans[1].size(); i1++) {
      ss[len - 4] = 'A' + ans[1][i1];
      for (int i2 = 0; i2 < ans[2].size(); i2++) {
        ss[len - 3] = 'A' + ans[2][i2];
        for (int i3 = 0; i3 < ans[3].size(); i3++) {
          ss[len - 2] = 'A' + ans[3][i3];
          for (int i4 = 0; i4 < ans[4].size(); i4++) {
            ss[len - 1] = 'A' + ans[4][i4];
            num[ss]++;
          }
        }
      }
    }
  }
}
char a[222], b[222];
map<string, char> id;
int main() {
  int n;
  scanf("%d ", &n);
  while (n--) update();
  int k;
  scanf("%d ", &k);
  while (k--) {
    scanf("%s %s", a, b);
    char c;
    if (a[0] == 'i')
      c = 'A' + 1;
    else if (a[0] == 'd')
      c = 'A' + 2;
    else
      c = 'A' + 3;
    id[b] = c;
  }
  int q;
  scanf("%d ", &q);
  while (q--) {
    gets(s), ss.clear();
    int nn = 0;
    for (char *t = strtok(s, tmp); t; t = strtok(0, tmp)) {
      nn++;
      if (nn == 1) ss = t, ss += "$";
      if (nn > 1) ss.push_back(id[t]);
    }
    while (nn++ < 6) ss.push_back('A' - 1);
    printf("%d\n", num[ss]);
  }
}
