#include <bits/stdc++.h>
using namespace std;
vector<string> GetTypes(string s) {
  int pos = 1;
  vector<string> Typs;
  while (pos < s.length() - 1) {
    string type = "";
    while ((s[pos] != ',') && (pos < s.length() - 1)) {
      type += s[pos];
      pos++;
    }
    pos++;
    Typs.push_back(type);
  }
  return Typs;
}
string DelSpace(string s) {
  string tempS = "";
  for (int i = (0); i < s.length(); i++)
    if ((s[i] != ' ')) tempS += s[i];
  s = tempS;
  return s;
}
int main() {
  string s, tempS, proName, type, varName;
  map<string, vector<string> > Pros;
  map<string, string> Vars;
  map<string, int> CountOfPros;
  vector<string> Inputs;
  ;
  int n;
  cin >> n;
  ;
  cin.ignore();
  for (int i = (0); i < n; i++) {
    getline(cin, s);
    s = DelSpace(s);
    s = s.substr(4);
    proName = s.substr(0, s.find('('));
    CountOfPros[proName]++;
    tempS = proName;
    for (int j = (0); j < CountOfPros[tempS]; j++) {
      proName += '*';
    }
    Pros[proName] = GetTypes(s.substr(s.find('(')));
  };
  int m;
  cin >> m;
  ;
  cin.ignore();
  for (int i = (0); i < m; i++) {
    getline(cin, s);
    s = DelSpace(s);
    if (s[0] == 'i') {
      type = s.substr(0, 3);
      varName = s.substr(3);
    } else if (s[0] == 'd') {
      type = s.substr(0, 6);
      varName = s.substr(6);
    } else if (s[0] == 's') {
      type = s.substr(0, 6);
      varName = s.substr(6);
    }
    Vars[varName] = type;
  };
  int k;
  cin >> k;
  ;
  cin.ignore();
  for (int i = (0); i < k; i++) {
    long long ans = 0;
    getline(cin, s);
    s = DelSpace(s);
    proName = s.substr(0, s.find('('));
    Inputs = GetTypes(s.substr(s.find('(')));
    for (int j = (0); j < Inputs.size(); j++) {
      Inputs[j] = Vars[Inputs[j]];
    }
    string tempS = proName;
    for (int j = (0); j < CountOfPros[tempS]; j++) {
      proName += '*';
      bool b = true;
      if (Pros[proName].size() != Inputs.size())
        b = false;
      else
        for (int t = (0); t < min(Pros[proName].size(), Inputs.size()); t++) {
          if ((Pros[proName][t] != Inputs[t]) && (Pros[proName][t] != "T"))
            b = false;
        }
      if (b) ans++;
    }
    cout << ans << endl;
  }
  return 0;
}
