#include <bits/stdc++.h>
template <typename T>
T Abs(T a) {
  return a < 0 ? -a : a;
}
template <typename T>
T Max(T a, T b) {
  return a > b ? a : b;
}
template <typename T>
T Min(T a, T b) {
  return a < b ? a : b;
}
template <typename T>
T Gcd(T a, T b) {
  return (!b) ? a : Gcd(b, a % b);
}
template <typename T>
T Pow(T a, T b) {
  if (!b) return 1;
  T t = Pow(a, b / 2);
  return b % 2 ? a * t * t : t * t;
}
template <typename T>
inline void read(T &x) {
  T f = 1;
  char c;
  x = 0;
  for (c = getchar(); c < '0' || c > '9'; c = getchar())
    if (c == '-') f = -1;
  for (; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - '0';
  x *= f;
}
using fl = float;
using db = double;
using ll = long long;
using ull = unsigned long long;
const int mx = 1000005;
const int inf = 99999999;
const int intlim = 2147483648;
const db PI = acos(-1);
using namespace std;
int main() {
  std::vector<string> func;
  std::vector<string> para[10010];
  std::map<string, string> mp;
  int n, m, k;
  scanf("%d", &n);
  getchar();
  for (int i = 0; i < n; ++i) {
    string str;
    getline(cin, str);
    string str2 = str, tmp;
    for (int j = 0; j < str2.size(); ++j)
      if (str2[j] == '(' || str2[j] == ')' || str2[j] == ',') str2[j] = ' ';
    stringstream s(str2);
    s >> tmp;
    s >> tmp;
    func.push_back(tmp);
    while (s >> tmp) para[i].push_back(tmp);
  }
  scanf("%d", &m);
  for (int i = 0; i < m; ++i) {
    string tmp1, tmp2;
    cin >> tmp1 >> tmp2;
    mp[tmp2] = tmp1;
  }
  scanf("%d", &k);
  getchar();
  for (int i = 0; i < k; ++i) {
    string str, str2;
    getline(cin, str);
    str2 = str;
    for (int j = 0; j < str2.size(); ++j)
      if (str2[j] == '(' || str2[j] == ')' || str2[j] == ',') str2[j] = ' ';
    string tmp, tmp2;
    stringstream s(str2);
    std::vector<string> v;
    s >> tmp;
    while (s >> tmp2) v.push_back(tmp2);
    int c = 0;
    for (int j = 0; j < func.size(); ++j) {
      if (tmp != func[j]) continue;
      if (v.size() != para[j].size()) continue;
      int f = 1;
      for (int k = 0; k < v.size(); ++k) {
        if (para[j][k] == "T") continue;
        if (para[j][k] != mp[v[k]]) {
          f = 0;
          break;
        }
      }
      if (f) c++;
    }
    cout << c << '\n';
  }
  return 0;
}
