#include <bits/stdc++.h>
using namespace std;
static const double EPS = 1e-10;
map<string, string> tval;
map<string, vector<vector<string> > > ftable;
int match(string fname, vector<string> plist) {
  int result = 0;
  for (int i = 0; i < ftable[fname].size(); ++i) {
    bool ok = true;
    if (ftable[fname][i].size() != plist.size()) continue;
    for (int j = 0; j < ftable[fname][i].size(); ++j) {
      if (ftable[fname][i][j] == "T" || ftable[fname][i][j] == tval[plist[j]]) {
      } else {
        ok = false;
        break;
      }
    }
    if (ok) ++result;
  }
  return result;
}
int main() {
  string tmp;
  int N;
  cin >> N;
  getline(cin, tmp);
  vector<string> func;
  for (int i = 0; i < N; ++i) {
    getline(cin, tmp);
    func.push_back(tmp);
  }
  int M;
  cin >> M;
  getline(cin, tmp);
  vector<string> vari;
  for (int i = 0; i < M; ++i) {
    getline(cin, tmp);
    vari.push_back(tmp);
  }
  int K;
  cin >> K;
  getline(cin, tmp);
  vector<string> cl;
  for (int i = 0; i < K; ++i) {
    getline(cin, tmp);
    cl.push_back(tmp);
  }
  for (int i = 0; i < vari.size(); ++i) {
    stringstream ss;
    ss << vari[i];
    string tp, nm;
    ss >> tp >> nm;
    tval[nm] = tp;
  }
  for (int i = 0; i < func.size(); ++i) {
    int j = 0;
    while (func[i][j] == ' ') ++j;
    while (func[i][j] != ' ') ++j;
    while (func[i][j] == ' ') ++j;
    string fnm;
    while (func[i][j] != ' ' && func[i][j] != '(') {
      fnm += func[i][j];
      ++j;
    }
    while (func[i][j] != '(') ++j;
    ++j;
    vector<string> tlist;
    while (1) {
      while (func[i][j] == ' ') ++j;
      string tpe;
      while (func[i][j] != ',' && func[i][j] != ' ' && func[i][j] != ')') {
        tpe += func[i][j];
        ++j;
      }
      tlist.push_back(tpe);
      while (func[i][j] == ' ') ++j;
      while (func[i][j] != ',' && func[i][j] != ')') ++j;
      if (func[i][j] == ')') break;
      ++j;
    }
    ftable[fnm].push_back(tlist);
  }
  for (int i = 0; i < K; ++i) {
    int j = 0;
    while (cl[i][j] == ' ') ++j;
    string fnm;
    while (cl[i][j] != '(' && cl[i][j] != ' ') {
      fnm += cl[i][j];
      ++j;
    }
    while (cl[i][j] != '(') ++j;
    ++j;
    vector<string> plist;
    while (1) {
      while (cl[i][j] == ' ') ++j;
      string pnm;
      while (cl[i][j] != ' ' && cl[i][j] != ',' && cl[i][j] != ')') {
        pnm += cl[i][j];
        ++j;
      }
      plist.push_back(pnm);
      while (cl[i][j] == ' ') ++j;
      while (cl[i][j] != ',' && cl[i][j] != ')') ++j;
      if (cl[i][j] == ')') break;
      ++j;
    }
    cout << match(fnm, plist) << endl;
    ;
  }
}
