#include <bits/stdc++.h>
using namespace std;
map<string, vector<vector<string>>> a;
map<string, string> b;
char buffer[1001];
pair<string, vector<string>> read() {
  gets(buffer);
  for (int i = 0; buffer[i]; i++) {
    if (buffer[i] == '(' || buffer[i] == ')' | buffer[i] == ',') {
      buffer[i] = ' ';
    }
  }
  istringstream stream(buffer);
  pair<string, vector<string>> ret;
  stream >> ret.first;
  string temp;
  while (stream >> temp) {
    ret.second.push_back(temp);
  }
  return ret;
}
int main() {
  int N;
  scanf("%d\n", &N);
  while (N--) {
    string NOTHING;
    cin >> NOTHING;
    pair<string, vector<string>> p = read();
    a[p.first].push_back(p.second);
  }
  scanf("%d\n", &N);
  while (N--) {
    string type, name;
    cin >> type >> name;
    b[name] = type;
  }
  scanf("%d\n", &N);
  while (N--) {
    pair<string, vector<string>> p = read();
    string name = p.first;
    vector<string> args = p.second;
    for (int i = 0; i < args.size(); i++) {
      args[i] = b[args[i]];
    }
    vector<vector<string>> all = a[name];
    int cnt = 0;
    for (int i = 0; i < all.size(); i++) {
      if (all[i].size() == args.size()) {
        bool ok = 1;
        for (int j = 0; j < args.size(); j++) {
          if (all[i][j] != "T" && all[i][j] != args[j]) {
            ok = 0;
            break;
          }
        }
        if (ok) cnt++;
      }
    }
    printf("%d\n", cnt);
  }
}
