#include <bits/stdc++.h>
using namespace std;
int n, k, l;
vector<string> ss[1100];
vector<pair<string, string> > var;
void parse(string s, int num, bool fl = true) {
  string str;
  int ii = 0;
  while (s[ii] == ' ') ++ii;
  if (fl)
    while (s[ii] != ' ') {
      ++ii;
    }
  while (s[ii] == ' ') ++ii;
  str = "";
  while (s[ii] != ' ' && s[ii] != '(') {
    str += s[ii];
    ++ii;
  }
  ss[num].push_back(str);
  while (s[ii] == ' ' || s[ii] == '(') ++ii;
  bool f = false;
  while (!f) {
    str = "";
    while (s[ii] == ' ' || s[ii] == ',' || s[ii] == '(') ++ii;
    while (s[ii] != ' ' && s[ii] != ',') {
      if (s[ii] == ')') {
        f = true;
        break;
      }
      str += s[ii];
      ++ii;
    }
    if (f && str.length() == 0) break;
    ss[num].push_back(str);
  }
}
int main() {
  cin >> n;
  int i, j, jj, r;
  char s[120], ts[120];
  string str, tstr;
  cin.getline(s, 119);
  for (i = 0; i < n; ++i) {
    cin.getline(s, 119);
    str.assign(s, strlen(s));
    parse(str, i);
  }
  cin >> k;
  for (i = 0; i < k; ++i) {
    cin >> s >> ts;
    str.assign(s, strlen(s));
    tstr.assign(ts, strlen(ts));
    var.push_back(make_pair(str, tstr));
  }
  cin >> l;
  cin.getline(s, 119);
  for (i = 0; i < l; ++i) {
    cin.getline(s, 119);
    str.assign(s, strlen(s));
    ss[n + 1].clear();
    parse(str, n + 1, false);
    for (j = 1; j < ss[n + 1].size(); ++j) {
      for (jj = 0; jj < k; ++jj)
        if (var[jj].second == ss[n + 1][j]) ss[n + 1][j] = var[jj].first;
    }
    r = 0;
    for (j = 0; j < n; ++j) {
      jj = 0;
      if (ss[j][0] == ss[n + 1][0] && ss[j].size() == ss[n + 1].size())
        for (jj = 0; jj < ss[j].size(); ++jj)
          if (ss[j][jj] != "T" && ss[j][jj] != ss[n + 1][jj]) break;
      if (jj == ss[j].size()) ++r;
    }
    cout << r << endl;
  }
  return 0;
}
