#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
inline long long read() {
  bool flag = 1;
  long long x = 0;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') flag = 0;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = (x << 1) + (x << 3) + c - '0';
    c = getchar();
  }
  return (flag ? x : ~(x - 1));
}
long long n, m, k, vis;
map<string, vector<vector<long long> > > fc;
map<string, string> va;
map<string, long long> ch;
vector<long long> v;
string s, x, fn;
void solve() {
  x = "", fn = "";
  v.clear();
  getline(cin, s);
  for (long long i = 0; i < s.size(); i++) {
    if (s[i] == ' ') {
      if (!vis && x.size()) {
        vis = 1;
        x = "";
      }
      continue;
    }
    if (s[i] == '(') {
      fn = x;
      x = "";
      continue;
    }
    if (s[i] == ',' || s[i] == ')') {
      if (x.size()) {
        v.push_back(ch[x]);
        x = "";
      }
      if (s[i] == ')') break;
      continue;
    }
    x += s[i];
  }
}
signed main() {
  n = read();
  ch["int"] = 1;
  ch["double"] = 2;
  ch["string"] = 4;
  ch["T"] = 7;
  while (n--) {
    vis = 0;
    solve();
    fc[fn].push_back(v);
  }
  m = read();
  while (m--) {
    string s1, s2;
    cin >> s1 >> s2;
    ch[s2] = ch[s1];
  }
  k = read();
  while (k--) {
    vis = 1;
    solve();
    long long ans = 0;
    for (long long i = 0; i < fc[fn].size(); i++)
      if (fc[fn][i].size() == v.size()) {
        long long ok = 1;
        for (long long l = 0; l < v.size(); l++) {
          long long f1 = fc[fn][i][l], f2 = f1 | v[l];
          if (f1 != f2) {
            ok = 0;
            break;
          }
        }
        ans += ok;
      }
    cout << ans << endl;
  }
  return 0;
}
