#include <bits/stdc++.h>
using namespace std;
map<string, vector<string> > procedures;
map<string, char> variables;
bool match(string params, string signature) {
  if (params.size() != signature.size()) return false;
  for (unsigned int i = 0; i < params.size(); i++) {
    if (signature[i] != 'T' && params[i] != signature[i]) return false;
  }
  return true;
}
int countmatches(string procedure, string params) {
  vector<string> ps = procedures[procedure];
  int count = 0;
  for (unsigned int i = 0; i < ps.size(); i++) {
    if (match(params, ps[i])) count++;
  }
  return count;
}
bool isWord(int c) {
  return (c == 'T') || (c >= (int)'a' && c <= 'z') || (c >= '0' && c <= '9');
}
bool isDelim(int c) { return !isWord(c); }
bool read(string& res) {
  res = "";
  while (isDelim(cin.peek())) {
    char c = cin.get();
  }
  while (isWord(cin.peek())) {
    res += (char)cin.get();
  }
  while (isDelim(cin.peek())) {
    char c = cin.get();
    if (c == ')') {
      return false;
    }
  }
  return true;
}
int main() {
  int n, m, k;
  cin >> n;
  for (int i = 0; i < n; i++) {
    string rubbish, procedure, param, sig = "";
    read(rubbish);
    read(procedure);
    while (read(param)) {
      sig += param[0];
    }
    sig += param[0];
    procedures[procedure].push_back(sig);
  }
  cin >> m;
  for (int i = 0; i < m; i++) {
    string type, name;
    read(type);
    read(name);
    variables[name] = type[0];
  }
  cin >> k;
  for (int i = 0; i < k; i++) {
    string procedure, param, params = "";
    read(procedure);
    while (read(param)) {
      params += variables[param];
    }
    params += variables[param];
    cout << countmatches(procedure, params) << "\n";
  }
}
