#include <bits/stdc++.h>
using namespace std;
struct Proc {
  string name;
  vector<string> args;
  bool matchesTo(const Proc &p) {
    if (name != p.name) return false;
    if (args.size() != p.args.size()) return false;
    for (int i = 0; i < args.size(); i++) {
      if (p.args[i] == "T") continue;
      if (args[i] != p.args[i]) return false;
    }
    return true;
  }
};
Proc readProc(bool readVoid) {
  Proc p;
  char buf[21];
  if (readVoid) scanf(" void");
  assert(scanf(" %[a-z0-9] (", buf) == 1);
  p.name = buf;
  while (scanf(" %[Ta-z0-9]", buf) == 1) {
    p.args.push_back(buf);
    scanf(" ,");
  }
  scanf(" )");
  return p;
}
int main() {
  int n;
  while (scanf("%d", &n) >= 1) {
    vector<Proc> ps(n);
    for (int i = 0; i < n; i++) ps[i] = readProc(true);
    map<string, string> types;
    int m;
    scanf(" %d", &m);
    while (m-- > 0) {
      char type[21], name[21];
      scanf(" %s %s", type, name);
      types[name] = type;
    }
    scanf(" %d", &m);
    while (m-- > 0) {
      Proc p = readProc(false);
      for (int i = 0; i < p.args.size(); i++) p.args[i] = types[p.args[i]];
      int cnt = 0;
      for (int i = 0; i < n; i++)
        if (p.matchesTo(ps[i])) cnt++;
      printf("%d\n", cnt);
    }
  }
  return 0;
}
