#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  string tmp;
  map<string, vector<vector<string> > > m;
  for (int i = 0; i < n; i++) {
    cin >> tmp;
    getline(cin, tmp);
    bool f = false;
    string name;
    vector<string> v;
    for (int j = 0; j < tmp.length(); j++) {
      string s;
      while (j < tmp.length() &&
             ((tmp[j] >= 'a' && tmp[j] <= 'z') ||
              (tmp[j] >= '0' && tmp[j] <= '9') || tmp[j] == 'T'))
        s += tmp[j++];
      if (!s.empty()) {
        if (f)
          v.push_back(s);
        else {
          name = s;
          f = true;
        }
      }
    }
    m[name].push_back(v);
  }
  int V;
  cin >> V;
  map<string, string> v;
  for (int i = 0; i < V; i++) {
    string type, name;
    cin >> type >> name;
    v[name] = type;
  }
  int k;
  scanf("%i\n", &k);
  for (int i = 0; i < k; i++) {
    getline(cin, tmp);
    string name;
    int j = 0;
    while (tmp[j] != '(') {
      if (tmp[j] != ' ') name += tmp[j];
      j++;
    }
    vector<string> a;
    while (j < tmp.length()) {
      string s;
      while (j < tmp.length() &&
             ((tmp[j] >= 'a' && tmp[j] <= 'z') ||
              (tmp[j] >= '0' && tmp[j] <= '9') || tmp[j] == 'T'))
        s += tmp[j++];
      if (!s.empty()) {
        a.push_back(v[s]);
      }
      j++;
    }
    int ans = 0;
    for (int k = 0; k < m[name].size(); k++) {
      bool eq = true;
      if (a.size() != m[name][k].size()) continue;
      for (int j = 0; j < a.size(); j++)
        if (a[j] != m[name][k][j] && m[name][k][j] != "T") {
          eq = false;
          break;
        }
      if (eq) ans++;
    }
    cout << ans << endl;
  }
  return 0;
}
