#include <bits/stdc++.h>
using namespace std;
bool iguales(vector<string>& x, vector<string>& y) {
  for (int i = (int)0; i < (int)x.size(); i++) {
    if (x[i] == "T" || y[i] == "T") continue;
    if (!(x[i] == y[i])) return false;
  }
  return true;
}
int main() {
  map<string, vector<vector<string> > > mapa;
  map<string, string> peso;
  int n, m, k;
  scanf("%d\n", &n);
  string linea, nom, alfa, beta;
  while (n--) {
    getline(cin, linea);
    for (int i = (int)0; i < (int)linea.size(); i++)
      if (linea[i] == '(' || linea[i] == ')' || linea[i] == ',') linea[i] = ' ';
    vector<string> x;
    stringstream flujo(linea);
    while (flujo >> linea) x.push_back(linea);
    nom = x[1];
    x.erase(x.begin());
    x.erase(x.begin());
    mapa[nom].push_back(x);
  }
  cin >> m;
  while (m--) {
    cin >> alfa >> beta;
    peso[beta] = alfa;
  }
  scanf("%d\n", &k);
  while (k--) {
    getline(cin, linea);
    for (int i = (int)0; i < (int)linea.size(); i++)
      if (linea[i] == '(' || linea[i] == ')' || linea[i] == ',') linea[i] = ' ';
    vector<string> x;
    stringstream flujo(linea);
    int cc = 0;
    while (flujo >> linea) {
      if (cc == 0) {
        nom = linea;
        cc = 1;
      } else
        x.push_back(peso[linea]);
    }
    map<string, vector<vector<string> > >::iterator iter;
    iter = mapa.find(nom);
    if (iter != mapa.end()) {
      vector<vector<string> > r = iter->second;
      int tot = 0;
      for (int i = (int)0; i < (int)r.size(); i++) {
        vector<string> second = r[i];
        if (x.size() == second.size()) {
          if (iguales(x, second)) tot++;
        }
      }
      cout << tot << endl;
    } else
      cout << 0 << endl;
  }
}
