#include <bits/stdc++.h>
using namespace std;
struct Prog {
  string name, now[10];
  int num;
  bool operator==(Prog k) {
    if (name == k.name)
      if (num == k.num) {
        for (int i = 0; i < num; i++) {
          if (now[i] == "T" || now[i] == k.now[i]) continue;
          return false;
        }
        return true;
      }
    return false;
  }
};
string Del(string s) {
  string ans = "";
  for (int i = 0; i < s.length(); i++)
    if (s[i] != ' ') ans += s[i];
  return ans;
}
vector<Prog> p;
map<string, string> va;
int n, m, k;
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    string v;
    cin >> v;
    getline(cin, v);
    Prog Pr;
    string tmp = "";
    v = Del(v);
    int k = 0;
    for (int i = 0; i < v.size(); i++) {
      if (v[i] == '(') {
        Pr.name = tmp;
        tmp = "";
        continue;
      } else if (v[i] == ',' || v[i] == ')') {
        Pr.now[k++] = tmp;
        tmp = "";
        continue;
      } else
        tmp += v[i];
    }
    Pr.num = k;
    p.push_back(Pr);
  }
  cin >> k;
  for (int i = 1; i <= k; i++) {
    string tt, tr;
    cin >> tt >> tr;
    va[tr] = tt;
  }
  cin >> m;
  cin.ignore();
  for (int i = 1; i <= m; i++) {
    string v;
    getline(cin, v);
    Prog Pr;
    string tmp = "";
    v = Del(v);
    int k = 0;
    for (int i = 0; i < v.size(); i++) {
      if (v[i] == '(') {
        Pr.name = tmp;
        tmp = "";
        continue;
      } else if (v[i] == ',' || v[i] == ')') {
        Pr.now[k++] = va[tmp];
        tmp = "";
        continue;
      } else
        tmp += v[i];
    }
    Pr.num = k;
    int ans = 0;
    for (int j = 0; j < p.size(); j++) {
      if (p[j] == Pr) ans++;
    }
    cout << ans << endl;
  }
}
