#include <bits/stdc++.h>
using namespace std;
int n;
string s, t;
map<string, string> var;
map<string, vector<vector<string>>> proc;
void preprocess(string& t) {
  string d = "(),";
  for (char& c : t)
    if (d.find(c) != -1) c = ' ';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n;
  cin.ignore();
  while (n--) {
    getline(cin, s);
    preprocess(s);
    stringstream ss(s);
    ss >> s >> t;
    auto& v = proc[t];
    v.emplace_back();
    while (ss >> s) v.back().emplace_back(s);
  }
  cin >> n;
  while (n--) {
    cin >> s >> t;
    var[t] = s;
  }
  cin >> n;
  cin.ignore();
  while (n--) {
    getline(cin, s);
    preprocess(s);
    stringstream ss(s);
    ss >> t;
    vector<string> p;
    while (ss >> s) p.emplace_back(var[s]);
    int cnt = 0;
    for (auto& v : proc[t]) {
      if (v.size() == p.size()) {
        bool flag = true;
        for (int i = 0; i < v.size(); i++) flag &= v[i] == "T" || v[i] == p[i];
        cnt += flag;
      }
    }
    cout << cnt << '\n';
  }
  return 0;
}
