#include <bits/stdc++.h>
using namespace std;
struct func {
  string name;
  vector<string> params;
} arr[1005];
map<string, string> vars;
func ParseFunction(string str, bool declaration = true) {
  for (int i = 0; i < str.size(); ++i) {
    if (str[i] == '(' || str[i] == ',' || str[i] == ')') {
      str[i] = ' ';
    }
  }
  istringstream ss(str);
  vector<string> params;
  string var;
  while (ss >> var) {
    params.push_back(var);
  }
  if (declaration) {
    params.erase(params.begin());
  }
  func result;
  result.name = params[0];
  params.erase(params.begin());
  result.params = params;
  return result;
}
int main() {
  string line;
  int n;
  getline(cin, line);
  sscanf(line.c_str(), "%d", &n);
  for (int i = 0; i < n; ++i) {
    getline(cin, line);
    arr[i] = ParseFunction(line);
  }
  int m;
  getline(cin, line);
  sscanf(line.c_str(), "%d", &m);
  for (int i = 0; i < m; ++i) {
    string type, name;
    getline(cin, line);
    istringstream ss(line);
    ss >> type >> name;
    vars[name] = type;
  }
  int k;
  getline(cin, line);
  sscanf(line.c_str(), "%d", &k);
  for (int i = 0; i < k; ++i) {
    getline(cin, line);
    func caller = ParseFunction(line, false);
    for (int i = 0; i < caller.params.size(); ++i) {
      caller.params[i] = vars[caller.params[i]];
    }
    int good = 0;
    for (int j = 0; j < n; ++j) {
      if (caller.name == arr[j].name &&
          caller.params.size() == arr[j].params.size()) {
        bool failed = false;
        for (int k = 0; k < caller.params.size(); ++k) {
          if (caller.params[k] != arr[j].params[k] && arr[j].params[k] != "T") {
            failed = true;
          }
        }
        if (!failed) {
          ++good;
        }
      }
    }
    cout << good << "\n";
  }
  return 0;
}
