#include <bits/stdc++.h>
using namespace std;
vector<string> han[1005];
const string types[3] = {"int", "double", "string"};
map<string, string> call;
map<pair<string, vector<string> >, int> cnt;
void meiju(string& nme, vector<string> arg, int pos) {
  if (arg.size() == pos) {
    cnt[make_pair(nme, arg)]++;
    return;
  }
  if (arg[pos] == "T") {
    for (int i = 0; i < 3; i++) {
      arg[pos] = types[i];
      meiju(nme, arg, pos + 1);
    }
  } else
    meiju(nme, arg, pos + 1);
}
int main() {
  int num;
  string s;
  cin >> num;
  cin.ignore();
  while (num--) {
    getline(cin, s);
    for (int i = 0; i < s.size(); i++)
      if (s[i] == '(' || s[i] == ',' || s[i] == ')') s[i] = ' ';
    istringstream ss(s);
    string hh;
    ss >> hh >> hh;
    vector<string> buff;
    string tmp;
    while (ss >> tmp) buff.push_back(tmp);
    meiju(hh, buff, 0);
  }
  cin >> num;
  for (int i = 0; i < num; i++) {
    string tmp, namel;
    cin >> tmp >> namel;
    call[namel] = tmp;
  }
  cin >> num;
  cin.ignore();
  for (int i = 0; i < num; i++) {
    getline(cin, s);
    for (int i = 0; i < s.size(); i++)
      if (s[i] == '(' || s[i] == ',' || s[i] == ')') s[i] = ' ';
    istringstream ss(s);
    string nnl;
    ss >> nnl;
    vector<string> buff;
    string tmp;
    while (ss >> tmp) buff.push_back(call[tmp]);
    cout << cnt[make_pair(nnl, buff)] << endl;
  }
  return 0;
}
