#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:256000000")
template <class T>
inline T sqr(T a) {
  return a * a;
}
struct f {
  string name;
  string par[5];
  int q;
};
bool operator==(const f &l, const f &r) {
  if (l.q != r.q || l.name != r.name) return 0;
  for (int i = 0; i < l.q; ++i)
    if (l.par[i] != r.par[i] && l.par[i] != "T") return 0;
  return 1;
}
map<string, string> var;
int n, k;
f func[1 << 10];
f parsef(string &s) {
  f res;
  int k = s.find("(");
  int l = s.find("d");
  ++l;
  while (s[l] == ' ') ++l;
  int r = k;
  --r;
  while (s[r] == ' ') --r;
  res.name = s.substr(l, r - l + 1);
  ++k;
  bool b = 0;
  for (int i = 0; i < 5; ++i) {
    int t = s.find(",", k);
    if (t == -1) {
      t = s.find(")");
      res.q = i + 1;
      b = 1;
    }
    r = t - 1;
    while (s[r] == ' ') --r;
    while (s[k] == ' ') ++k;
    res.par[i] = s.substr(k, r - k + 1);
    k = t + 1;
    if (b) return res;
  }
  return res;
}
f parseq(string &s) {
  f res;
  int k = s.find("(");
  int l = 0;
  while (s[l] == ' ') ++l;
  int r = k;
  --r;
  while (s[r] == ' ') --r;
  res.name = s.substr(l, r - l + 1);
  ++k;
  bool b = 0;
  for (int i = 0; i < 5; ++i) {
    int t = s.find(",", k);
    if (t == -1) {
      t = s.find(")");
      res.q = i + 1;
      b = 1;
    }
    r = t - 1;
    while (s[r] == ' ') --r;
    while (s[k] == ' ') ++k;
    res.par[i] = var[s.substr(k, r - k + 1)];
    k = t + 1;
    if (b) return res;
  }
  return res;
}
int main() {
  cin >> n;
  string s;
  getline(cin, s);
  for (int i = 0; i < n; ++i) {
    getline(cin, s);
    func[i] = parsef(s);
  }
  cin >> k;
  for (int i = 0; i < k; ++i) {
    string t;
    cin >> s >> t;
    var[t] = s;
  }
  int v;
  cin >> v;
  getline(cin, s);
  for (int i = 0; i < v; ++i) {
    getline(cin, s);
    int res = 0;
    f w = parseq(s);
    for (int j = 0; j < n; ++j)
      if (func[j] == w) ++res;
    printf("%d\n", res);
  }
  return 0;
}
