#include <bits/stdc++.h>
using namespace std;
void f(int &x) {
  string buf;
  getline(cin, buf);
  istringstream in(buf);
  in >> x;
}
void split(const string &s, vector<string> &mas) {
  string word;
  for (int i = 0; i < s.size(); i++) {
    if (s[i] == ' ' || s[i] == ',' || s[i] == '(' || s[i] == ')') {
      if (word != "") mas.push_back(word);
      word = "";
    } else
      word += s[i];
  }
  if (word != "") mas.push_back(word);
}
int main() {
  int n;
  f(n);
  vector<vector<string> > procs(n);
  for (int i = 0; i < n; i++) {
    string buf;
    getline(cin, buf);
    split(buf, procs[i]);
  }
  int m;
  f(m);
  map<string, string> vartypes;
  for (int i = 0; i < m; i++) {
    string buf;
    getline(cin, buf);
    istringstream in(buf);
    string a, b;
    in >> a >> b;
    vartypes[b] = a;
  }
  int k;
  f(k);
  for (int i = 0; i < k; i++) {
    string buf;
    getline(cin, buf);
    vector<string> tmp;
    split(buf, tmp);
    for (int j = 1; j < tmp.size(); j++) tmp[j] = vartypes[tmp[j]];
    int cnt = 0;
    for (int j = 0; j < procs.size(); j++) {
      if (procs[j][1] != tmp[0]) continue;
      if (procs[j].size() != tmp.size() + 1) continue;
      bool bad = false;
      for (int l = 1; !bad && l < tmp.size(); l++)
        if (procs[j][l + 1] == "T" || procs[j][l + 1] == tmp[l])
          ;
        else
          bad = true;
      if (!bad) cnt++;
    }
    cout << cnt << "\n";
  }
  return 0;
}
