#include <bits/stdc++.h>
using namespace std;
map<string, int> type;
string trim(string s) {
  int pos = 0;
  while (s[pos] == ' ') pos++;
  s = s.substr(pos);
  pos = s.size() - 1;
  while (s[pos] == ' ') pos--;
  return s.substr(0, pos + 1);
}
vector<string> split(string s, char sepor = ',') {
  vector<string> res;
  string curr = "";
  for (int i = 0; i < s.size(); i++)
    if (s[i] == ',') {
      res.push_back(trim(curr));
      curr = "";
    } else {
      curr += s[i];
    }
  res.push_back(trim(curr));
  return res;
}
pair<string, string> parse_name(string s) {
  int pos = 0;
  while (s[pos] != '(') pos++;
  string name = s.substr(0, pos);
  s = s.substr(pos + 1);
  pos = s.size() - 1;
  while (s[pos] != ')') pos--;
  s = s.substr(0, pos);
  return make_pair(trim(name), s);
}
pair<string, vector<int> > parse(string s, bool isntcall = true,
                                 char sepor = ',') {
  if (isntcall) {
    int pos = 0;
    while (s[pos] != 'v') pos++;
    while (s[pos] != 'o') pos++;
    while (s[pos] != 'i') pos++;
    while (s[pos] != 'd') pos++;
    pos++;
    while (s[pos] == ' ') pos++;
    s = s.substr(pos);
  }
  pair<string, string> temp_str = parse_name(s);
  vector<string> temp = split(temp_str.second);
  vector<int> res;
  for (int i = 0; i < temp.size(); i++) res.push_back(type[temp[i]]);
  return make_pair(temp_str.first, res);
}
pair<string, vector<int> > proc[1100];
map<string, int> var;
void init() {
  type["T"] = 0;
  type["int"] = 1;
  type["double"] = 2;
  type["string"] = 3;
}
int main() {
  init();
  char buff[10000];
  gets(buff);
  int n;
  sscanf(buff, "%d", &n);
  for (int i = 0; i < n; i++) {
    gets(buff);
    string s = buff;
    proc[i] = parse(s);
  }
  int m;
  cin >> m;
  for (int i = 0; i < m; i++) {
    string s, t;
    cin >> s >> t;
    type[t] = type[s];
  }
  int k;
  gets(buff);
  gets(buff);
  sscanf(buff, "%d", &k);
  for (int i = 0; i < k; i++) {
    gets(buff);
    string s = buff;
    pair<string, vector<int> > call = parse(s, false);
    int res = 0;
    for (int j = 0; j < n; j++)
      if (proc[j].first == call.first &&
          proc[j].second.size() == call.second.size()) {
        bool ok = true;
        for (int q = 0; q < proc[j].second.size(); q++) {
          int x = (proc[j].second)[q];
          int y = (call.second)[q];
          if (x > 0 && x != y) ok = false;
        }
        if (ok) res++;
      }
    cout << res << endl;
  }
  return 0;
}
