#include <bits/stdc++.h>
using namespace std;
int main() {
  int i, j, N, cnt, k;
  vector<pair<string, vector<string> > > func;
  cin >> N;
  string s, sp;
  vector<string> vec;
  pair<string, vector<string> > candidate;
  getline(cin, s);
  for (i = 0; i < N; ++i) {
    getline(cin, s);
    for (j = 0; j < s.size(); ++j) {
      if (s[j] == ')' || s[j] == '(' || s[j] == ',') {
        s[j] = ' ';
      }
    }
    vec.clear();
    istringstream sin(s);
    while (sin >> sp) {
      vec.push_back(sp);
    }
    vector<string> clear;
    candidate.first = vec[1];
    candidate.second = clear;
    for (j = 2; j < vec.size(); ++j) {
      candidate.second.push_back(vec[j]);
    }
    func.push_back(candidate);
  }
  map<string, string> types;
  cin >> N;
  getline(cin, s);
  for (i = 0; i < N; ++i) {
    getline(cin, s);
    istringstream sin(s);
    vec.clear();
    while (sin >> sp) {
      vec.push_back(sp);
    }
    types[vec[1]] = vec[0];
  }
  cin >> N;
  getline(cin, sp);
  for (i = 0; i < N; ++i) {
    cnt = 0;
    getline(cin, sp);
    for (j = 0; j < sp.size(); ++j) {
      if (sp[j] == ')' || sp[j] == '(' || sp[j] == ',') {
        sp[j] = ' ';
      }
    }
    istringstream sin(sp);
    vec.clear();
    while (sin >> s) {
      vec.push_back(s);
    }
    for (j = 0; j < func.size(); ++j) {
      bool ok = true;
      if (func[j].first == vec[0]) {
        if (vec.size() - 1 != func[j].second.size())
          continue;
        else {
          for (k = 1; k < vec.size(); ++k) {
            if (types[vec[k]] == func[j].second[k - 1] ||
                func[j].second[k - 1] == "T") {
              continue;
            } else {
              ok = !ok;
              break;
            }
          }
          if (ok) {
            cnt++;
          }
        }
      }
    }
    cout << cnt << endl;
  }
  return 0;
}
