#include <bits/stdc++.h>
using namespace std;
const int MaxN = 1024;
template <typename T>
void checkmin(T& lhs, const T& rhs) {
  if (lhs > rhs) lhs = rhs;
}
template <typename T>
void checkmax(T& lhs, const T& rhs) {
  if (lhs < rhs) lhs = rhs;
}
int T;
char buf[MaxN];
vector<string> v[MaxN];
vector<string> parse(const char* s, bool fd = false) {
  vector<string> ret;
  string buf;
  while (*s == ' ') s++;
  if (fd) {
    while (*s != ' ') s++;
    while (*s == ' ') s++;
  }
  buf = "";
  while (*s != ' ' && *s != '(') {
    buf += *s++;
  }
  ret.push_back(buf);
  while (*s == ' ' || *s == '(') s++;
  while (*s != ')') {
    buf = "";
    while (*s != ' ' && *s != ',' && *s != ')') {
      buf += *s++;
    }
    ret.push_back(buf);
    while (*s == ' ' || *s == ',') s++;
  }
  return ret;
}
map<string, string> mp;
bool check(const vector<string>& vp, const vector<string>& v) {
  if (vp.size() != v.size()) return false;
  if (vp[0] != v[0]) return false;
  for (int i = 1; i < (int)v.size(); i++)
    if (mp.find(vp[i]) == mp.end() || (v[i] != "T" && mp[vp[i]] != v[i]))
      return false;
  return true;
}
int sol(const vector<string>& vp) {
  int ret = 0;
  for (int i = 0; i < T; i++)
    if (check(vp, v[i])) ret++;
  return ret;
}
int main() {
  int M;
  scanf("%d", &T);
  gets(buf);
  for (int i = 0; i < T; i++) {
    gets(buf);
    v[i] = parse(buf, true);
  }
  scanf("%d", &M);
  while (M--) {
    char a[MaxN], b[MaxN];
    scanf("%s%s", a, b);
    mp[b] = a;
  }
  scanf("%d", &M);
  gets(buf);
  while (M--) {
    gets(buf);
    vector<string> vp = parse(buf);
    printf("%d\n", sol(vp));
  }
  return 0;
}
