#include <bits/stdc++.h>
using namespace std;
char pN[1000];
char tp[1000];
vector<pair<string, vector<string>>> V;
map<string, string> M;
bool Comp(const pair<string, vector<string>>& a,
          const pair<string, vector<string>>& b) {
  if (a.first != b.first) return (false);
  if (a.second.size() != b.second.size()) return (false);
  for (int i = 0; i < a.second.size(); i++) {
    if (a.second[i] == b.second[i]) continue;
    if (a.second[i] != "T") return (false);
  }
  return (true);
}
int main() {
  int n;
  scanf("%d\n", &n);
  for (int i = 0; i < n; i++) {
    scanf("void %[^(] (", pN);
    vector<string> tmp;
    while (scanf("%[^,)]", tp) > 0) {
      scanf(",");
      int len = strlen(tp);
      string tmps;
      for (int i = 0; i < len; i++) {
        if (tp[i] == ' ') continue;
        tmps += tp[i];
      }
      tmp.push_back(tmps);
    }
    scanf(")\n");
    int len = strlen(pN);
    string tmps;
    for (int i = 0; i < len; i++) {
      if (pN[i] == ' ') continue;
      tmps += pN[i];
    }
    V.push_back(make_pair(tmps, tmp));
  }
  int m;
  cin >> m;
  for (int i = 0; i < m; i++) {
    string tp, vN;
    cin >> tp >> vN;
    M[vN] = tp;
  }
  int k;
  scanf("%d\n", &k);
  for (int i = 0; i < k; i++) {
    int res = 0;
    scanf("%[^(] (", pN);
    vector<string> tmp;
    while (scanf("%[^,)]", tp) > 0) {
      scanf(",");
      int len = strlen(tp);
      string tmps;
      for (int i = 0; i < len; i++) {
        if (tp[i] == ' ') continue;
        tmps += tp[i];
      }
      tmp.push_back(M[tmps]);
    }
    scanf(")\n");
    int len = strlen(pN);
    string tmps;
    for (int i = 0; i < len; i++) {
      if (pN[i] == ' ') continue;
      tmps += pN[i];
    }
    pair<string, vector<string>> LOL = make_pair(tmps, tmp);
    for (int i = 0; i < V.size(); i++) {
      if (Comp(V[i], LOL)) res++;
    }
    printf("%d\n", res);
  }
  return (0);
}
