#include <bits/stdc++.h>
using namespace std;
const long long int mod = 998244353;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int T = clock();
  long long int n;
  string k;
  getline(cin, k);
  n = stoi(k);
  map<string, vector<vector<string>>> call;
  for (long long int j = 0; j < n; j++) {
    string s, k;
    getline(cin, s);
    long long int i = 0;
    while (i < s.size() && s[i] == ' ') i++;
    while (i < s.size() && s[i] != ' ') k += s[i], i++;
    k.clear();
    while (i < s.size() && s[i] == ' ') i++;
    while (i < s.size() && s[i] != ' ' && s[i] != '(') k += s[i], i++;
    string p = k;
    vector<string> r;
    while (i < s.size()) {
      k.clear();
      while (i < s.size() &&
             (s[i] == ' ' || s[i] == '(' || s[i] == ')' || s[i] == ','))
        i++;
      while (i < s.size() && s[i] != ' ' && s[i] != ')' && s[i] != ',')
        k += s[i], i++;
      r.push_back(k);
    }
    call[p].push_back(r);
  }
  long long int m;
  getline(cin, k);
  m = stoi(k);
  map<string, string> var;
  for (long long int j = 0; j < m; j++) {
    string s, k;
    getline(cin, s);
    long long int i = 0;
    while (i < s.size() && s[i] == ' ') i++;
    while (i < s.size() && s[i] != ' ') k += s[i], i++;
    string r;
    while (i < s.size() && s[i] == ' ') i++;
    while (i < s.size() && s[i] != ' ') r += s[i], i++;
    var[r] = k;
  }
  long long int r;
  getline(cin, k);
  r = stoi(k);
  for (long long int j = 0; j < r; j++) {
    string s, k;
    getline(cin, s);
    long long int i = 0;
    while (i < s.size() && s[i] == ' ') i++;
    while (i < s.size() && s[i] != ' ' && s[i] != '(') k += s[i], i++;
    string p = k;
    vector<string> r;
    while (i < s.size()) {
      k.clear();
      while (i < s.size() &&
             (s[i] == ' ' || s[i] == '(' || s[i] == ')' || s[i] == ','))
        i++;
      while (i < s.size() && s[i] != ' ' && s[i] != ')' && s[i] != ',')
        k += s[i], i++;
      r.push_back(var[k]);
    }
    vector<vector<string>> a = call[p];
    long long int cnt = 0;
    for (long long int i = 0; i < a.size(); i++) {
      bool ok = true;
      if (r.size() != a[i].size()) continue;
      for (long long int k = 0; k < a[i].size(); k++) {
        if (a[i][k] == "T" || a[i][k] == r[k])
          ;
        else
          ok = false;
      }
      if (ok) cnt++;
    }
    cout << cnt << "\n";
  }
  cerr << "\n\nTIME: " << (double)(clock() - T) / CLOCKS_PER_SEC << " sec\n";
  T = clock();
  return 0;
}
