#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9;
const long long N = 1e3 + 1;
const long long mod = 1 << 30;
const long double eps = 1E-7;
string w;
bool k, f;
int n, m, p, q;
string x, t, a[N];
map<string, int> mp;
vector<int> V, g[N];
void check(int i) {
  if (t != "") {
    if (!k) {
      a[i] = t;
      k = true;
    } else {
      g[i].push_back(mp[t]);
    }
  }
}
void work() {
  if (t != "") {
    if (!k) {
      w = t;
      k = true;
    } else {
      V.push_back(mp[t]);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n;
  mp["T"] = 4;
  mp["int"] = 1;
  mp["string"] = 2;
  mp["double"] = 3;
  for (int i = 1; i <= n; i++) {
    cin >> x;
    k = f = false;
    while (!f) {
      t = "";
      cin >> x;
      p = x.size();
      if (x[p - 1] == ')') f = true;
      for (int j = 0; j < p; j++) {
        if (x[j] == ',' or x[j] == '(' or x[j] == ')') {
          check(i);
          t = "";
          continue;
        }
        t += x[j];
      }
      check(i);
    }
  }
  cin >> m;
  for (int i = 1; i <= m; i++) {
    cin >> x >> t;
    mp[t] = mp[x];
  }
  cin >> m;
  for (int i = 1; i <= m; i++) {
    V.clear();
    k = f = false;
    while (!f) {
      t = "";
      cin >> x;
      p = x.size();
      if (x[p - 1] == ')') f = true;
      for (int j = 0; j < p; j++) {
        if (x[j] == ',' or x[j] == '(' or x[j] == ')') {
          work();
          t = "";
          continue;
        }
        t += x[j];
      }
      work();
    }
    q = 0;
    for (int j = 1; j <= n; j++) {
      if (a[j] != w or g[j].size() != V.size()) continue;
      p = 0;
      for (int h = 0; h < V.size(); h++) {
        if (g[j][h] == 4 or g[j][h] == V[h]) p = p + 1;
      }
      if (p == V.size()) q = q + 1;
    }
    cout << q << endl;
  }
}
