#include <bits/stdc++.h>
using namespace std;
int nextint() {
  int t;
  scanf("%d", &t);
  return t;
}
string types[3] = {"int", "double", "string"};
map<pair<string, vector<string> >, int> cnt;
map<string, string> var;
void add(string& name, vector<string>& v, int pos) {
  if (pos == v.size()) {
    cnt[make_pair(name, v)]++;
  } else {
    if (v[pos] == "T") {
      for (int i = 0; i < (3); i++) {
        v[pos] = types[i];
        add(name, v, pos + 1);
      }
      v[pos] = "T";
    } else
      add(name, v, pos + 1);
  }
}
int main() {
  int n = nextint();
  {
    string str;
    getline(cin, str);
  }
  for (int i = 0; i < (n); i++) {
    string str;
    getline(cin, str);
    for (int i = 0; i < (str.size()); i++)
      if (str[i] == '(' || str[i] == ')' || str[i] == ',') str[i] = ' ';
    istringstream in(str);
    in >> str;
    string name;
    in >> name;
    vector<string> v;
    while (in >> str) {
      v.push_back(str);
    }
    add(name, v, 0);
  }
  int m = nextint();
  for (int i = 0; i < (m); i++) {
    string type, name;
    cin >> type >> name;
    var[name] = type;
  }
  int k = nextint();
  {
    string str;
    getline(cin, str);
  }
  for (int i = 0; i < (k); i++) {
    string str;
    getline(cin, str);
    for (int i = 0; i < (str.size()); i++)
      if (str[i] == '(' || str[i] == ')' || str[i] == ',') str[i] = ' ';
    istringstream in(str);
    string name;
    in >> name;
    vector<string> v;
    while (in >> str) {
      v.push_back(var[str]);
    }
    printf("%d\n", cnt[make_pair(name, v)]);
  }
  return 0;
}
