#include <bits/stdc++.h>
using namespace std;
const int maxn = 1005;
int n, m, t;
bool ok(string& n1, vector<string>& pv1, string& n2, vector<string> pv2) {
  if (n1 != n2) return false;
  if (pv1.size() != pv2.size()) return false;
  for (int i = 0; i < pv1.size(); ++i)
    if (pv1[i] != "T" && pv1[i] != pv2[i]) return false;
  return true;
}
map<string, string> var_t;
inline bool valid_c(int c) { return c != ' ' && c != '\t' && c != '\n'; }
pair<string, vector<string> > get_fun(int g = true) {
  pair<string, vector<string> > ans;
  int c = getchar();
  if (g) {
    while (!valid_c(c)) c = getchar();
    while (valid_c(c)) c = getchar();
  }
  while (!valid_c(c)) c = getchar();
  string n, s;
  n += char(c);
  c = getchar();
  while (valid_c(c) && c != '(') {
    n += char(c);
    c = getchar();
  }
  vector<string> sv;
  while (true) {
    while (!valid_c(c)) c = getchar();
    if (c == ')') break;
    c = getchar();
    while (!valid_c(c)) c = getchar();
    s = "";
    s += char(c);
    c = getchar();
    while (valid_c(c) && c != ',' && c != ')') {
      s += char(c);
      c = getchar();
    }
    sv.push_back(s);
  }
  return make_pair(n, sv);
}
vector<string> to_t(vector<string>& var_n) {
  vector<string> ret;
  for (int i = 0; i < var_n.size(); ++i) ret.push_back(var_t[var_n[i]]);
  return ret;
}
char s1[maxn], s2[maxn];
pair<string, vector<string> > p[maxn], temp;
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) p[i] = get_fun();
  scanf("%d", &m);
  for (int i = 0; i < m; ++i) {
    scanf("%s%s", &s1, &s2);
    var_t[string(s2)] = string(s1);
  }
  scanf("%d", &t);
  for (int i = 0; i < t; ++i) {
    temp = get_fun(false);
    int ans = 0;
    for (int j = 0; j < n; ++j)
      if (ok(p[j].first, p[j].second, temp.first, to_t(temp.second))) ++ans;
    printf("%d\n", ans);
  }
  return 0;
}
