#include <bits/stdc++.h>
using namespace std;
int n, m, k;
map<string, string> mp;
struct cadongllas {
  int num;
  string var[7];
  string name;
} ask[1009], funk[1009];
bool equal(cadongllas x, cadongllas y) {
  if (x.num != y.num) return 0;
  if (x.name != y.name) return 0;
  for (int i = 1; i <= x.num; i++)
    if (x.var[i] != y.var[i] && x.var[i] != "T") return 0;
  return 1;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    char blank[1009];
    scanf("%s", blank);
    while (1) {
      char ch = getchar();
      if (ch == '(') break;
      if (ch != ' ') ask[i].name += ch;
    }
    string s;
    getline(cin, s);
    int len = s.length();
    int now = 0;
    while (1) {
      while ((s[now] == ')' || s[now] == ',' || s[now] == ' ') && now < len)
        now++;
      if (now >= len) break;
      string nex;
      while (1) {
        nex += s[now++];
        if (s[now] == ')' || s[now] == ',' || s[now] == ' ' || now >= len)
          break;
      }
      ask[i].var[++ask[i].num] = nex;
      if (s[now] == ')') break;
    }
  }
  cin >> m;
  for (int i = 1; i <= m; i++) {
    string sa, sb;
    cin >> sa >> sb;
    mp[sb] = sa;
  }
  cin >> k;
  getchar();
  for (int i = 1; i <= k; i++) {
    while (1) {
      char ch = getchar();
      if (ch == '(') break;
      if (ch != ' ') funk[i].name += ch;
    }
    string s;
    getline(cin, s);
    int len = s.length(), now = 0;
    while (1) {
      while ((s[now] == ')' || s[now] == ',' || s[now] == ' ') && now < len)
        now++;
      if (now >= len) break;
      string nex;
      while (1) {
        nex += s[now++];
        if (s[now] == ')' || s[now] == ',' || s[now] == ' ' || now >= len)
          break;
      }
      funk[i].var[++funk[i].num] = mp[nex];
      if (s[now] == ')') break;
    }
    int ans = 0;
    for (int j = 1; j <= n; j++)
      if (equal(ask[j], funk[i])) ans++;
    cout << ans << endl;
  }
  return 0;
}
