#include <bits/stdc++.h>
using namespace std;
map<string, string> vars;
struct proc {
  string name, arg[10];
  int argn;
  proc(string v, bool V) {
    string til = "";
    int k = 0;
    for (int i = 0; i < v.length(); i++) {
      if (v[i] == '(') {
        name = til;
        til = "";
        continue;
      } else if (v[i] == ',' || v[i] == ')') {
        if (V)
          arg[k++] = vars[til];
        else
          arg[k++] = til;
        til = "";
        continue;
      } else
        til += v[i];
    }
    argn = k;
  }
  bool operator==(proc k) {
    if (name == k.name) {
      if (argn == k.argn) {
        for (int i = 0; i < argn; i++) {
          if (arg[i] == "T" || arg[i] == k.arg[i]) continue;
          return false;
        }
        return true;
      }
    }
    return false;
  }
};
vector<proc> p;
string DeleteSpaces(string k) {
  string ans = "";
  for (int i = 0; i < k.length(); i++)
    if (k[i] != ' ') ans += k[i];
  return ans;
}
int main() {
  int n, m, k;
  cin >> n;
  for (int i = 0; i < n; i++) {
    string v;
    cin >> v;
    getline(cin, v);
    proc Pro(DeleteSpaces(v), false);
    p.push_back(Pro);
  }
  cin >> k;
  for (int i = 0; i < k; i++) {
    string type, name;
    cin >> type >> name;
    vars[name] = type;
  }
  cin >> m;
  cin.ignore();
  for (int i = 0; i < m; i++) {
    string v;
    getline(cin, v);
    proc Pro(DeleteSpaces(v), true);
    int ans = 0;
    for (int j = 0; j < p.size(); j++) {
      if (p[j] == Pro) ans++;
    }
    cout << ans << endl;
  }
}
