#include <bits/stdc++.h>
using namespace std;
int n, p, q;
char ch;
string na, ty, al;
bool flag;
map<string, string> m1;
map<string, vector<vector<string> > > m2;
int main() {
  cin >> n;
  cin.ignore();
  for (int i = 1; i <= n; ++i) {
    getline(cin, al);
    int k = 0;
    for (int j = 0; j < al.size(); ++j) {
      if (al[j] == '(') al[j] = '\n';
      if (al[j] == ')') al[j] = ' ';
      if (al[j] == ',') al[j] = '\n';
      if (al[j] != ' ') al[k++] = al[j];
    }
    al.resize(k);
    al.erase(0, 4);
    istringstream s1(al);
    vector<string> v;
    s1 >> na;
    while (s1 >> ty) v.push_back(ty);
    m2[na].push_back(v);
  }
  cin >> p;
  cin.ignore();
  for (int i = 1; i <= p; ++i) {
    getline(cin, al);
    int k = 0;
    istringstream s2(al);
    vector<string> v;
    s2 >> ty;
    s2 >> na;
    m1[na] = ty;
  }
  cin >> q;
  cin.ignore();
  for (int i = 1; i <= q; ++i) {
    int ans = 0;
    getline(cin, al);
    int k = 0;
    for (int j = 0; j < al.size(); ++j) {
      if (al[j] == '(') al[j] = '\n';
      if (al[j] == ')') al[j] = ' ';
      if (al[j] == ',') al[j] = '\n';
      if (al[j] != ' ') al[k++] = al[j];
    }
    al.resize(k);
    istringstream s3(al);
    vector<string> v;
    s3 >> na;
    while (s3 >> ty) v.push_back(m1[ty]);
    for (int j = 0; j < m2[na].size(); ++j) {
      if (m2[na][j].size() != v.size()) continue;
      for (k = 0; k < m2[na][j].size(); ++k) {
        if (m2[na][j][k] == "T") continue;
        if (m2[na][j][k] != v[k]) break;
      }
      if (k == v.size()) ++ans;
    }
    cout << ans << "\n";
  }
  return 0;
}
