#include <bits/stdc++.h>
using namespace std;
struct Proc {
  string name;
  int t;
  vector<string> pars;
};
vector<Proc> procs;
map<string, string> vars;
void getProc() {
  Proc proc;
  char aux[1000];
  scanf("%*s");
  scanf(" %[0-9a-z] ", aux);
  proc.name = aux;
  proc.t = 0;
  while (1) {
    scanf(" %[^0-9a-zT] ", aux);
    if (aux[0] == ')') break;
    scanf(" %[0-9a-zT] ", aux);
    proc.t++;
    proc.pars.push_back(string(aux));
  }
  procs.push_back(proc);
}
void getVar() {
  char aux[1000];
  scanf("%s", aux);
  string s = aux;
  scanf("%s", aux);
  vars[string(aux)] = s;
}
void solve() {
  Proc proc;
  char aux[1000];
  scanf(" %[0-9a-z] ", aux);
  proc.name = aux;
  proc.t = 0;
  while (1) {
    scanf(" %[^0-9a-zT] ", aux);
    if (aux[0] == ')') break;
    scanf(" %[0-9a-zT] ", aux);
    proc.t++;
    proc.pars.push_back(vars[aux]);
  }
  int res = 0;
  for (int i = 0; i < procs.size(); ++i) {
    if (procs[i].name != proc.name) continue;
    if (procs[i].t != proc.t) continue;
    bool g = 1;
    for (int j = 0; j < proc.t && g; ++j) {
      if (procs[i].pars[j] == proc.pars[j]) continue;
      if (procs[i].pars[j] == "T")
        continue;
      else
        g = 0;
    }
    if (!g) continue;
    ++res;
  }
  printf("%d\n", res);
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    getProc();
  }
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    getVar();
  }
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    solve();
  }
  return 0;
}
