#include <bits/stdc++.h>
using namespace std;
string l, s1, s2;
int n, m, z, t;
string name[1010];
vector<int> par[1010];
map<string, int> mapi;
map<string, string> type;
int main() {
  mapi["T"] = t++;
  scanf("%d", &n);
  getline(cin, l);
  for (int i = 0; i < n; i++) {
    getline(cin, l);
    string f = "";
    for (int j = 0; j < l.size(); j++) {
      if (l[j] != ' ' && f == "") {
        while (1) {
          f += l[j], j++;
          if (l[j - 1] == 'd') break;
        }
        j--;
      } else if (l[j] != ' ' && f != "" && name[i] == "") {
        while (l[j] != ' ' && l[j] != '(') name[i] += l[j], j++;
      } else if (l[j] != ' ' && l[j] != '(' && name[i] != "") {
        string x;
        while (l[j] != ' ' && l[j] != ',' && l[j] != ')') x += l[j], j++;
        while ((l[j] == ' ' || l[j] == ',' || l[j] == ')') && j < l.size()) j++;
        if (mapi.find(x) == mapi.end()) mapi[x] = t++;
        par[i].push_back(mapi[x]);
        j--;
      }
    }
  }
  scanf("%d", &m);
  for (int i = 0; i < m; i++) {
    cin >> s1 >> s2;
    type[s2] = s1;
  }
  scanf("%d", &z);
  getline(cin, l);
  for (int i = 0; i < z; i++) {
    int res = 0;
    getline(cin, l);
    string Name;
    vector<int> vec;
    for (int j = 0; j < l.size(); j++) {
      if (l[j] != ' ' && Name == "") {
        while (l[j] != ' ' && l[j] != '(') Name += l[j], j++;
      } else if (l[j] != ' ' && l[j] != '(' && Name != "") {
        string x;
        while (l[j] != ' ' && l[j] != ',' && l[j] != ')') x += l[j], j++;
        while ((l[j] == ' ' || l[j] == ',' || l[j] == ')') && j < l.size()) j++;
        int p = -1;
        if (mapi.find(type[x]) != mapi.end()) p = mapi[type[x]];
        vec.push_back(p);
        j--;
      }
    }
    for (int j = 0; j < n; j++) {
      int flag = 0;
      if (name[j] != Name || par[j].size() != vec.size()) continue;
      for (int x = 0; x < vec.size(); x++) {
        if (vec[x] != par[j][x] && par[j][x] != 0) flag = 1;
      }
      if (flag == 0) res++;
    }
    printf("%d\n", res);
  }
  return 0;
}
