#include <bits/stdc++.h>
using namespace std;
int n = 0, v;
vector<string> proc[1000];
string names[1000];
map<string, string> type;
void readSpace() {
  char c;
  c = getchar();
  while (c == ' ' || c == '\n') {
    c = getchar();
  }
  cin.putback(c);
}
void readB(int i) {
  char c = ' ';
  string vd;
  cin >> vd;
  while (c == ' ') c = getchar();
  string name = "";
  while (c != '(' && c != ' ') {
    name += c;
    c = getchar();
  }
  if (c == ' ') {
    readSpace();
    getchar();
  }
  names[i] = name;
}
string readName() {
  char c;
  string name = "";
  c = getchar();
  while (c != '(' && c != ' ') {
    name += c;
    c = getchar();
  }
  if (c == ' ') {
    readSpace();
    getchar();
  }
  return name;
}
bool rt(int i) {
  readSpace();
  string s = "";
  char c = getchar();
  while (c != ')' && c != ',' && c != ' ') {
    s += c;
    c = getchar();
  }
  proc[i].push_back(s);
  if (c == ' ') {
    readSpace();
    c = getchar();
  }
  if (c == ')') return false;
  return true;
}
bool done;
string rvar() {
  readSpace();
  string s = "";
  char c = getchar();
  while (c != ')' && c != ',' && c != ' ') {
    s += c;
    c = getchar();
  }
  if (c == ' ') {
    readSpace();
    c = getchar();
  }
  if (c == ')') done = true;
  return s;
}
bool suits(string s1, string s2) {
  if (s1 == s2) return true;
  if (s2 == "T") return true;
  return false;
}
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    readB(i);
    while (rt(i))
      ;
  }
  cin >> v;
  string s1, s2;
  for (int i = 0; i < v; i++) {
    cin >> s1 >> s2;
    type.insert(make_pair(s2, s1));
  }
  int calls;
  cin >> calls;
  string name;
  vector<string> types;
  int cnt;
  for (int i = 0; i < calls; i++) {
    done = false;
    readSpace();
    types.clear();
    name = readName();
    cnt = 0;
    while (!done) {
      types.push_back(rvar());
    }
    for (int j = 0; j < n; j++) {
      if ((string)names[j] == (string)name && types.size() == proc[j].size()) {
        int h;
        for (h = 0; h < types.size(); h++) {
          if (!suits(type[types[h]], proc[j][h])) break;
        }
        if (h == types.size()) cnt++;
      }
    }
    cout << cnt << endl;
  }
  return 0;
}
