#include <bits/stdc++.h>
using namespace std;
int n, m, q;
map<string, string> x;
vector<vector<string> > p;
string nos(string s) {
  string w = "";
  for (auto it : s)
    if (it != ' ') w += it;
  return w;
}
bool comp(vector<string> a, vector<string> b) {
  if (a.size() != b.size() || a[0] != b[0]) return 0;
  for (int i = 1; i < a.size(); i++)
    if (a[i] != b[i] && a[i] != "T" && b[i] != "T") return 0;
  return 1;
}
int main() {
  cin >> n;
  string t, s;
  getline(cin, t);
  for (int i = 0; i < n; i++) {
    getline(cin, t);
    t = t.substr(t.find('d') + 1);
    vector<string> strings;
    istringstream f(t.substr(t.find('(') + 1, t.find(')') - t.find('(') - 1));
    t = nos(t.substr(0, t.find('(')));
    strings.push_back(t);
    while (getline(f, s, ',')) strings.push_back(nos(s));
    p.push_back(strings);
  }
  cin >> m;
  while (m--) {
    cin >> t >> s;
    x[s] = t;
  }
  cin >> q;
  getline(cin, t);
  while (q--) {
    getline(cin, t);
    vector<string> strings;
    istringstream f(t.substr(t.find('(') + 1, t.find(')') - t.find('(') - 1));
    t = nos(t.substr(0, t.find('(')));
    strings.push_back(t);
    while (getline(f, s, ',')) strings.push_back(nos(s));
    for (int i = 1; i < strings.size(); i++) strings[i] = x[strings[i]];
    int c = 0;
    for (auto it : p)
      if (comp(it, strings)) c++;
    cout << c << "\n";
  }
  return 0;
}
