#include <bits/stdc++.h>
using namespace std;
struct node {
  vector<char> name;
  vector<char> ty[5];
} a[1010];
node b;
map<string, string> mp;
int check(int k) {
  if (a[k].name.size() != b.name.size()) return 0;
  for (int i = 0; i < (int)b.name.size(); i++) {
    if (a[k].name[i] != b.name[i]) return 0;
  }
  for (int i = 0; i < 5; i++) {
    if (a[k].ty[i].size() == 1 && a[k].ty[i][0] == 'T') {
      if (b.ty[i].size() == 0) return 0;
      continue;
    }
    if (a[k].ty[i].size() != b.ty[i].size()) return 0;
    for (int j = 0; j < (int)b.ty[i].size(); j++) {
      if (a[k].ty[i][j] != b.ty[i][j]) return 0;
    }
  }
  return 1;
}
void ouput(node c) {
  for (int i = 0; i < (int)c.name.size(); i++) {
    printf("%c", c.name[i]);
  }
  printf(" ");
  for (int i = 0; i < 5; i++) {
    if (c.ty[i].size() == 0) continue;
    for (int j = 0; j < (int)c.ty[i].size(); j++) {
      printf("%c", c.ty[i][j]);
    }
    printf(" ");
  }
  printf("\n");
}
int main() {
  int n, m, q;
  char str[1010];
  char s1[110], s2[110];
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%s", str);
    gets(str);
    int j = 0;
    while (str[j] != '(') {
      if (str[j] != ' ') a[i].name.push_back(str[j]);
      j++;
    }
    int t = 0;
    for (; str[j] != ')'; j++) {
      int k = j + 1;
      while (str[k] != ',' && str[k] != ')') {
        if (str[k] != ' ') a[i].ty[t].push_back(str[k]);
        k++;
      }
      j = k - 1;
      t++;
    }
  }
  mp.clear();
  scanf("%d", &m);
  for (int i = 0; i < m; i++) {
    scanf("%s%s", s1, s2);
    mp[s2] = s1;
  }
  scanf("%d", &q);
  getchar();
  for (int i = 0; i < q; i++) {
    gets(str);
    int flag = 1;
    for (int j = 0; j < 5; j++) b.ty[j].clear();
    b.name.clear();
    int j = 0;
    while (str[j] != '(') {
      if (str[j] != ' ') b.name.push_back(str[j]);
      j++;
    }
    int t = 0;
    for (; str[j] != ')'; j++) {
      int k = j + 1;
      string S;
      S.clear();
      while (str[k] != ',' && str[k] != ')') {
        if (str[k] != ' ') S += str[k];
        k++;
      }
      j = k - 1;
      if (mp.find(S) == mp.end())
        flag = 0;
      else {
        S = mp[S];
        for (int p = 0; p < (int)S.size(); p++) b.ty[t].push_back(S[p]);
      }
      t++;
    }
    if (!flag) {
      printf("0\n");
      continue;
    }
    int ans = 0;
    for (int j = 0; j < n; j++) {
      if (check(j)) ans++;
    }
    printf("%d\n", ans);
  }
}
