#include <bits/stdc++.h>
using namespace std;
const int inf = (1 << 30) - 1;
const long long inf2 = (1 << 62) - 1;
const double eps = 1e-6;
map<string, string> val;
map<string, vector<vector<string> > > func;
string getstr(string s, int l, int r) {
  string re = "";
  for (int i = l; i <= r; i++)
    if (s[i] != ' ') re += s[i];
  return re;
}
int main() {
  int t;
  cin >> t;
  string gett;
  getline(cin, gett);
  while (t--) {
    string s;
    getline(cin, s);
    int l = 0;
    while (l < s.size() && s[l] == ' ') l++;
    l += 4;
    while (l < s.size() && s[l] == ' ') l++;
    int r = s.find('(');
    string fname = getstr(s, l, r - 1);
    l = r + 1;
    vector<string> v;
    while (l < s.size()) {
      while (l < s.size() && s[l] == ' ') l++;
      if (s[l] == 'i') {
        v.push_back("int");
      }
      if (s[l] == 'd') {
        v.push_back("double");
      }
      if (s[l] == 's') {
        v.push_back("string");
      }
      if (s[l] == 'T') {
        v.push_back("T");
      }
      while (l < s.size() && s[l] != ',') l++;
      l++;
    }
    func[fname].push_back(v);
  }
  cin >> t;
  while (t--) {
    string a, b;
    cin >> a >> b;
    val[b] = a;
  }
  cin >> t;
  getline(cin, gett);
  while (t--) {
    string s;
    getline(cin, s);
    int l = 0;
    while (l < s.size() && s[l] == ' ') l++;
    int r = l;
    while (r < s.size() && s[r] != ' ' && s[r] != '(') r++;
    string fname = getstr(s, l, r - 1);
    l = r + 1;
    if (func.find(fname) == func.end()) {
      puts("0");
      continue;
    }
    vector<string> v;
    while (l < s.size()) {
      while (l < s.size() && s[l] == ' ' || s[l] == '(') l++;
      int r = l;
      while (r < s.size() && s[r] != ')' && s[r] != ',') r++;
      string ss = val[getstr(s, l, r - 1)];
      if (ss != "") v.push_back(ss);
      l = r + 1;
    }
    int cnt = 0;
    vector<vector<string> > Find = func[fname];
    for (int i = 0; i < (1 << v.size()); i++) {
      vector<string> fnd = v;
      for (int j = 0; j < fnd.size(); j++)
        if ((i >> j) & 1) fnd[j] = "T";
      for (int j = 0; j < Find.size(); j++) {
        if (fnd == Find[j]) cnt++;
      }
    }
    cout << cnt << endl;
  }
  return 0;
}
