#include <bits/stdc++.h>
using namespace std;
string tmps, second;
int n, m, curpos, k;
string name[10000], pname;
vector<string> types[10000], ptypes;
map<string, string> type;
string next() {
  while (curpos < second.length() &&
         !(isalpha(second[curpos]) || isdigit(second[curpos])))
    ++curpos;
  if (curpos >= second.length()) return "";
  string word = "";
  while (isalpha(second[curpos]) || isdigit(second[curpos]))
    word += second[curpos++];
  return word;
}
bool ok(string &name, vector<string> &types) {
  if (name != pname) return false;
  if (types.size() != ptypes.size()) return false;
  for (int i = 0; i < types.size(); ++i) {
    if (types[i] != "T" && types[i] != ptypes[i]) return false;
  }
  return true;
}
int main() {
  cin >> n;
  getline(cin, second);
  for (int i = 0; i < n; ++i) {
    getline(cin, second);
    curpos = 0;
    next();
    name[i] = next();
    for (;;) {
      string tp = next();
      if (tp == "") break;
      types[i].push_back(tp);
    }
  }
  cin >> m;
  getline(cin, second);
  for (int i = 0; i < m; ++i) {
    getline(cin, second);
    curpos = 0;
    string tp = next();
    string nam = next();
    type[nam] = tp;
  }
  cin >> k;
  getline(cin, second);
  for (int i = 0; i < k; ++i) {
    getline(cin, second);
    curpos = 0;
    pname = next();
    ptypes.clear();
    for (;;) {
      string var = next();
      if (var == "") break;
      ptypes.push_back(type[var]);
    }
    int ans = 0;
    for (int j = 0; j < n; ++j)
      if (ok(name[j], types[j])) ++ans;
    cout << ans << endl;
  }
  return 0;
}
