#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:200000000")
using namespace std;
template <typename T>
inline T Abs(T a) {
  return a > 0 ? a : -a;
}
template <typename T>
inline T sqr(T a) {
  return a * a;
}
template <typename T>
inline void relaxMin(T &a, T b) {
  if (b < a) a = b;
}
template <typename T>
inline void relaxMax(T &a, T b) {
  if (b > a) a = b;
}
const int INF = INT_MAX / 2 - 1;
const long double EPS = 1E-12;
const long double PI = 3.1415926535897932384626433832795;
vector<pair<string, vector<int>>> f;
char s[400];
char s2[400];
void trim_s() {
  int pos = 0;
  int len = strlen(s);
  for (int i(0), _bb(len); i < _bb; ++i) {
    if (s[i] == '(' || s[i] == ')' || s[i] == ',') {
      s2[pos++] = ' ';
      s2[pos++] = s[i];
      s2[pos++] = ' ';
    } else
      s2[pos++] = s[i];
  }
}
int type(string s) {
  int t = -1;
  if (s == "int")
    t = 0;
  else if (s == "double")
    t = 1;
  else if (s == "string")
    t = 2;
  else if (s == "T")
    t = 3;
  else {
    if (!(false)) {
      ++*(char *)0;
    }
  };
  return t;
}
void scan_f() {
  gets(s);
  trim_s();
  stringstream ss(s2);
  string s, name;
  ss >> s >> name;
  ss >> s;
  vector<int> v;
  while (ss >> s) {
    v.push_back(type(s));
    ss >> s;
    if (s == ")") break;
    {
      if (!(s == ",")) {
        ++*(char *)0;
      }
    };
  }
  f.push_back(make_pair(name, v));
}
map<string, int> vartype;
void solve() {
  int n;
  scanf("%d\n", &n);
  for (int i(0), _bb(n); i < _bb; ++i) scan_f();
  int m;
  scanf("%d\n", &m);
  for (int i(0), _bb(m); i < _bb; ++i) {
    gets(s2);
    stringstream ss(s2);
    string name, t;
    ss >> t >> name;
    int tt = type(t);
    vartype[name] = tt;
  }
  int test;
  scanf("%d\n", &test);
  for (int ttest(0), _bb(test); ttest < _bb; ++ttest) {
    gets(s);
    trim_s();
    stringstream ss(s2);
    string name, s;
    ss >> name >> s;
    vector<int> v;
    while (ss >> s) {
      v.push_back(vartype[s]);
      ss >> s;
      if (s == ")") break;
      {
        if (!(s == ",")) {
          ++*(char *)0;
        }
      };
    }
    int ans = 0;
    for (int i(0), _bb(n); i < _bb; ++i) {
      if (f[i].first == name) {
        int sz = f[i].second.size();
        bool ok = sz == v.size();
        if (ok)
          for (int j(0), _bb(sz); j < _bb; ++j) {
            if (f[i].second[j] != v[j] && f[i].second[j] != 3) ok = false;
          }
        if (ok) ans++;
      }
    }
    cout << ans << endl;
  }
}
int main() {
  solve();
  return 0;
}
