#include <bits/stdc++.h>
using namespace std;
vector<string> split(string s) {
  vector<string> res;
  string str;
  s.push_back(',');
  for (int i = 0; i < ((int)s.size()); ++i) {
    if (s[i] == ',' || s[i] == ')') {
      if (!str.empty()) {
        res.push_back(str);
        str.clear();
      }
      continue;
    }
    str.push_back(s[i]);
  }
  return res;
}
int main() {
  int n;
  cin >> n;
  vector<string> a;
  vector<vector<string> > b;
  string s;
  getline(cin, s);
  for (int i = 0; i < n; ++i) {
    cin >> s;
    getline(cin, s);
    string str;
    for (int j = 0; j < ((int)s.size()); ++j)
      if (s[j] != ' ') str.push_back(s[j]);
    int pos = str.find("(");
    string new_s = str.substr(pos + 1);
    a.push_back(str.substr(0, pos));
    b.push_back(split(new_s));
  }
  int m;
  cin >> m;
  map<string, string> d;
  for (int i = 0; i < m; ++i) {
    cin >> s;
    string str;
    cin >> str;
    d[str] = s;
  }
  int k;
  cin >> k;
  getline(cin, s);
  for (int i = 0; i < k; ++i) {
    int result = 0;
    getline(cin, s);
    string str;
    for (int j = 0; j < ((int)s.size()); ++j)
      if (s[j] != ' ') str.push_back(s[j]);
    int pos = str.find("(");
    string new_s = str.substr(pos + 1);
    string name = str.substr(0, pos);
    vector<string> res = split(new_s);
    vector<string> val;
    for (int j = 0; j < ((int)res.size()); ++j) val.push_back(d[res[j]]);
    for (int j = 0; j < n; ++j) {
      if (name != a[j]) continue;
      if (((int)res.size()) != ((int)b[j].size())) continue;
      bool ok = true;
      for (int k = 0; k < ((int)res.size()); ++k) {
        if (b[j][k] != "T" && b[j][k] != val[k]) {
          ok = false;
          break;
        }
      }
      if (ok) ++result;
    }
    cout << result << endl;
  }
  return 0;
}
