#include <bits/stdc++.h>
using std::cin;
using std::cout;
void cleanupBuf(char* buf) {
  int bufLen = strlen(buf);
  for (int i = 0; i < bufLen; ++i) {
    if (buf[i] == '(' || buf[i] == ')' || buf[i] == ',') {
      buf[i] = ' ';
    }
  }
}
int main() {
  std::ios_base::sync_with_stdio(false);
  cout.precision(11);
  char buf[1000];
  std::multimap<std::string, std::vector<std::string> > procedures;
  int N;
  cin >> N;
  cin.getline(buf, 1000);
  for (int line = 0; line < N; ++line) {
    cin.getline(buf, 1000);
    cleanupBuf(buf);
    std::stringstream ss(buf);
    std::string v;
    ss >> v;
    std::string name;
    ss >> name;
    std::vector<std::string> types;
    while (!ss.eof()) {
      std::string type;
      ss >> type;
      types.push_back(type);
    }
    procedures.insert(
        std::multimap<std::string, std::vector<std::string> >::value_type(
            name, types));
  }
  int M;
  cin >> M;
  cin.getline(buf, 1000);
  std::map<std::string, std::string> variables;
  for (int i = 0; i < M; ++i) {
    cin.getline(buf, 1000);
    std::stringstream ss(buf);
    std::string type;
    ss >> type;
    std::string name;
    ss >> name;
    variables[name] = type;
  }
  int K;
  cin >> K;
  cin.getline(buf, 1000);
  for (int i = 0; i < K; ++i) {
    cin.getline(buf, 1000);
    cleanupBuf(buf);
    std::stringstream ss(buf);
    std::string name;
    ss >> name;
    std::vector<std::string> types;
    while (!ss.eof()) {
      std::string varName;
      ss >> varName;
      types.push_back(variables[varName]);
    }
    int ans = 0;
    for (std::multimap<std::string, std::vector<std::string> >::iterator
             procedure = procedures.find(name);
         procedure != procedures.end(); ++procedure) {
      if (procedure->first != name) {
        break;
      }
      std::vector<std::string>& pTypes = procedure->second;
      if (pTypes.size() != types.size()) {
        continue;
      }
      bool ok = true;
      for (size_t i = 0; i < types.size(); ++i) {
        if (pTypes[i] == "T") {
          continue;
        }
        if (pTypes[i] != types[i]) {
          ok = false;
          break;
        }
      }
      if (ok) {
        ++ans;
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
