#include <bits/stdc++.h>
using namespace std;
map<string, string> type;
vector<vector<string> > decls;
int n, m, k;
void replace(string& s, char a, char b) {
  for (int i = 0; i < s.size(); i++)
    if (s[i] == a) s[i] = b;
}
int main() {
  string line;
  string tok;
  string temp;
  cin >> n;
  cin.ignore();
  decls.resize(n);
  vector<string> cur;
  for (int i = 0; i < n; i++) {
    getline(cin, line);
    replace(line, '(', ' ');
    replace(line, ')', ' ');
    replace(line, ',', ' ');
    istringstream sin(line);
    sin >> tok;
    while (sin >> tok) decls[i].push_back(tok);
  }
  cin >> m;
  cin.ignore();
  for (int i = 0; i < m; i++) {
    getline(cin, line);
    istringstream sin(line);
    sin >> temp >> tok;
    type[tok] = temp;
  }
  cin >> k;
  cin.ignore();
  int matches;
  bool good;
  for (int i = 0; i < k; i++) {
    cur.clear();
    matches = 0;
    getline(cin, line);
    replace(line, '(', ' ');
    replace(line, ')', ' ');
    replace(line, ',', ' ');
    istringstream sin(line);
    while (sin >> tok) cur.push_back(tok);
    for (int j = 0; j < n; j++) {
      if (cur.size() != decls[j].size()) continue;
      good = true;
      if (cur[0] != decls[j][0]) continue;
      for (int k = 1; k < decls[j].size(); k++) {
        if (decls[j][k] == "T" || decls[j][k] == type[cur[k]]) continue;
        good = false;
        break;
      }
      matches += good;
    }
    cout << matches << '\n';
  }
  return 0;
}
