#include <bits/stdc++.h>
using namespace std;
map<string, pair<int, vector<string> > > mp1[1111];
map<int, string> mp11;
map<string, pair<int, vector<string> > > mp2[1111];
map<int, string> mp22;
map<string, string> mp3;
string vo[1111];
string a[1111], b[1111];
string ca[1111];
int main() {
  int n;
  cin >> n;
  for (int i = 0; i <= n; i++) getline(cin, vo[i]);
  for (int i = 1; i <= n; i++) {
    string s = "";
    int cnt = 0;
    int j;
    for (j = 0; vo[i][j] != 'd'; j++)
      ;
    j++;
    for (; vo[i][j] != '('; j++)
      if (vo[i][j] != ' ') s += vo[i][j];
    int a[111];
    int ptr = 0;
    for (int k = j; k < vo[i].size(); k++)
      if (vo[i][k] == ',' || vo[i][k] == '(' || vo[i][k] == ')') a[ptr++] = k;
    for (int k = 0; k < ptr - 1; k++) {
      string p = "";
      for (int d = a[k] + 1; d < a[k + 1]; d++)
        if (vo[i][d] != ' ') p += vo[i][d];
      cnt++;
      mp1[i][s].second.push_back(p);
    }
    mp1[i][s].first = cnt;
    mp11[i] = s;
  }
  int m;
  cin >> m;
  for (int i = 0; i < m; i++) cin >> a[i] >> b[i];
  for (int i = 0; i < m; i++) mp3[b[i]] = a[i];
  int r;
  cin >> r;
  for (int i = 0; i <= r; i++) getline(cin, ca[i]);
  for (int i = 1; i <= r; i++) {
    string s = "";
    int cnt = 0;
    int j = 0;
    for (; ca[i][j] != '('; j++)
      if (ca[i][j] != ' ') s += ca[i][j];
    int a[111];
    int ptr = 0;
    for (int k = j; k < ca[i].size(); k++)
      if (ca[i][k] == ',' || ca[i][k] == '(' || ca[i][k] == ')') a[ptr++] = k;
    for (int k = 0; k < ptr - 1; k++) {
      string p = "";
      for (int d = a[k] + 1; d < a[k + 1]; d++)
        if (ca[i][d] != ' ') p += ca[i][d];
      cnt++;
      mp2[i][s].second.push_back(mp3[p]);
    }
    mp2[i][s].first = cnt;
    mp22[i] = s;
  }
  for (int i = 1; i <= r; i++) {
    int ans = 0;
    for (int j = 1; j <= n; j++) {
      bool flag = true;
      if (mp11[j] == mp22[i] &&
          mp1[j][mp11[j]].first == mp2[i][mp22[i]].first) {
        for (int k = 0; k < mp2[i][mp22[i]].first; k++)
          if (mp2[i][mp22[i]].second[k] != mp1[j][mp11[j]].second[k] &&
              mp1[j][mp11[j]].second[k] != "T")
            flag = false;
      } else
        flag = false;
      if (flag == true) ans++;
    }
    cout << ans << endl;
  }
  return 0;
}
