#include <bits/stdc++.h>
using namespace std;
char tmp[120];
int n_t, n_v, n_p;
map<string, string> lei;
vector<string> voids[1005];
vector<string> call;
inline bool cmp(vector<string>& v1, vector<string>& v2) {
  int i = 0, j = 0;
  while (v1[i] == "" && i < v1.size()) i++;
  while (v2[j] == "" && j < v2.size()) j++;
  if (v1[i] == v2[j]) {
    i++;
    j++;
  } else {
    return false;
  }
  while (i < v1.size() && j < v2.size()) {
    if (v1[i] == v2[j]) {
      i++;
      j++;
    } else if (v1[i] == "T" || v2[j] == "T") {
      i++;
      j++;
    } else {
      return false;
    }
  }
  return (v1.size() == i && v2.size() == j);
}
inline string readtype(string& t, int& p) {
  string s = "";
  while (islower(t[p]) || isupper(t[p]) || isdigit(t[p])) s += t[p++];
  return s;
}
int main() {
  int i, j;
  string t;
  scanf("%d", &n_t);
  for (i = 0; i < n_t; i++) {
    scanf("%s", tmp);
    gets(tmp);
    t = tmp;
    int l = t.size();
    int p = 0;
    while (t[p] == ' ') ++p;
    for (; p < l; p++) {
      if (t[p] == ' ' || t[p] == '(' || t[p] == ')' || t[p] == ',') continue;
      voids[i].push_back(readtype(t, p));
    }
  }
  scanf("%d", &n_v);
  for (i = 0; i < n_v; i++) {
    string l, nam;
    scanf("%s", tmp), l = tmp;
    scanf("%s", tmp), nam = tmp;
    lei[nam] = l;
  }
  scanf("%d", &n_p);
  gets(tmp);
  for (i = 0; i < n_p; i++) {
    call.clear();
    gets(tmp);
    t = tmp;
    int p = 0, l = t.size();
    while (t[p] == ' ') ++p;
    for (; p < l; p++) {
      if (t[p] == ' ' || t[p] == '(' || t[p] == ')' || t[p] == ',') continue;
      string ss = readtype(t, p);
      if (!call.empty())
        call.push_back(lei[ss]);
      else
        call.push_back(ss);
    }
    int cnt = 0;
    for (int j = 0; j < n_t; j++)
      if (cmp(call, voids[j])) cnt++;
    printf("%d\n", cnt);
  }
  return 0;
}
