#include <bits/stdc++.h>
using namespace std;
map<string, vector<vector<string> > > params;
map<string, string> trans;
pair<char, string> read_to_break() {
  string s = "";
  do {
    char sym = getchar();
    if (sym == '(' || sym == ')' || sym == ',') return make_pair(sym, s);
    if (sym != ' ' && sym != '\n') s += sym;
  } while (1);
}
bool eq(vector<string> a, vector<string> b) {
  if ((int)(a).size() != (int)(b).size()) return 0;
  for (int i = 0; i < (int)(a).size(); i++) {
    if (!(trans[a[i]] == b[i] || b[i] == "T")) return false;
  }
  return true;
}
int main() {
  int n, m, k;
  cin >> n;
  for (int i = 0; i < n; i++) {
    string trash;
    cin >> trash;
    string name = read_to_break().second;
    vector<string> desc;
    while (1) {
      pair<char, string> token = read_to_break();
      desc.push_back(token.second);
      if (token.first == ')') {
        params[name].push_back(desc);
        break;
      }
    }
  }
  cin >> m;
  for (int i = 0; i < m; i++) {
    string type, var;
    cin >> type >> var;
    trans[var] = type;
  }
  cin >> k;
  for (int i = 0; i < k; i++) {
    string proc = read_to_break().second;
    vector<string> desc;
    while (1) {
      pair<char, string> token = read_to_break();
      desc.push_back(token.second);
      if (token.first == ')') {
        break;
      }
    }
    int res = 0;
    for (int j = 0; j < (int)(params[proc]).size(); j++) {
      if (eq(desc, params[proc][j])) res++;
    }
    cout << res << endl;
  }
  return 0;
}
