#include <bits/stdc++.h>
using namespace std;
int n;
string Name[1005];
vector<string> para[1005];
int m;
map<string, string> variab;
int k;
string nam;
vector<string> curpars;
int res;
bool Equal(int v) {
  if (Name[v] != nam || para[v].size() != curpars.size()) return false;
  for (int i = 0; i < para[v].size(); i++) {
    string par = para[v][i];
    if (par != "T" && par != variab[curpars[i]]) return false;
  }
  return true;
}
int main() {
  string line;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    cin >> line;
    getline(cin, line);
    int p = line.find_first_not_of(" ");
    int next = line.find_first_of(" (", p + 1);
    Name[i] = line.substr(p, next - p);
    p = line.find_first_not_of(" (", next + 1);
    while (p != string::npos) {
      next = line.find_first_of(" ,)", p + 1);
      para[i].push_back(line.substr(p, next - p));
      p = line.find_first_not_of(" ,)", next + 1);
    }
  }
  scanf("%d", &m);
  while (m--) {
    string typ, nam;
    cin >> typ >> nam;
    variab[nam] = typ;
  }
  scanf("%d", &k);
  getline(cin, line);
  while (k--) {
    getline(cin, line);
    int p = line.find_first_not_of(" ");
    int next = line.find_first_of(" (", p + 1);
    nam = line.substr(p, next - p);
    curpars.clear();
    p = line.find_first_not_of(" (", next + 1);
    while (p != string::npos) {
      next = line.find_first_of(" ,)", p + 1);
      curpars.push_back(line.substr(p, next - p));
      p = line.find_first_not_of(" ,)", next + 1);
    }
    res = 0;
    for (int i = 0; i < n; i++) res += Equal(i);
    printf("%d\n", res);
  }
  return 0;
}
