#include <bits/stdc++.h>
using namespace std;
int n, m, k;
struct procedure {
  string name;
  string ptype[6];
  int pcnt;
  bool matchcall(procedure &call) {
    if (call.name != name) return false;
    if (call.pcnt != pcnt) return false;
    for (int i = 0; i < pcnt; i++)
      if (ptype[i] != "T" && call.ptype[i] != ptype[i]) return false;
    return true;
  }
} datp[1010];
map<string, string> vars;
int main() {
  string str;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> str >> str;
    datp[i].name = "";
    int j, len = str.length();
    for (j = 0; j < len && str[j] != '('; j++) datp[i].name += str[j];
    if (j >= len) cin >> str, len = str.length(), j = 0;
    while (str[j] != ')') {
      datp[i].ptype[datp[i].pcnt++] = "";
      for (j++; j < len && str[j] != ')' && str[j] != ','; j++)
        datp[i].ptype[datp[i].pcnt - 1] += str[j];
      if (datp[i].ptype[datp[i].pcnt - 1] == "") datp[i].pcnt--;
      if (j >= len) cin >> str, len = str.length(), j = -1;
    }
  }
  cin >> m;
  vars.clear();
  string strb;
  for (int i = 0; i < m; i++) {
    cin >> str >> strb;
    vars.insert(make_pair(strb, str));
  }
  cin >> k;
  procedure call;
  for (int i = 0; i < k; i++) {
    cin >> str;
    call.name = "";
    int j, len = str.length();
    for (j = 0; j < len && str[j] != '('; j++) call.name += str[j];
    if (j >= len) cin >> str, len = str.length(), j = 0;
    call.pcnt = 0;
    while (str[j] != ')') {
      call.ptype[call.pcnt++] = "";
      for (j++; j < len && str[j] != ')' && str[j] != ','; j++)
        call.ptype[call.pcnt - 1] += str[j];
      if (call.ptype[call.pcnt - 1] == "")
        call.pcnt--;
      else
        call.ptype[call.pcnt - 1] = vars[call.ptype[call.pcnt - 1]];
      if (j >= len) cin >> str, len = str.length(), j = -1;
    }
    int ans = 0;
    for (j = 0; j < n; j++)
      if (datp[j].matchcall(call)) ans++;
    cout << ans << endl;
  }
  return 0;
}
