#include <bits/stdc++.h>
using namespace std;
bool T;
int N, M, K;
char line[105], name[15], type[15];
string n_line;
vector<string> procedure[1005];
vector<string> calls[1005];
map<string, string> m;
string trim(char line[]) {
  int len = strlen(line);
  string buf = "";
  for (int i = 0; i < len; i++) {
    if (line[i] != ' ') buf += line[i];
  }
  return buf;
}
void decode(string conf, int idx) {
  int ii = 4;
  while (ii < (int)conf.size() && conf[ii] != '(') ii++;
  procedure[idx].push_back(conf.substr(4, ii - 4));
  ii++;
  int jj = ii;
  while (ii < (int)conf.size() && conf[ii] != ')') {
    while (jj < (int)conf.size() && conf[jj] != ',' && conf[jj] != ')') jj++;
    procedure[idx].push_back(conf.substr(ii, jj - ii));
    jj++;
    ii = jj;
  }
}
void decode2(string conf, int idx) {
  int ii = 0;
  while (ii < (int)conf.size() && conf[ii] != '(') ii++;
  calls[idx].push_back(conf.substr(0, ii));
  ii++;
  int jj = ii;
  while (ii < (int)conf.size() && conf[ii] != ')') {
    while (jj < (int)conf.size() && conf[jj] != ',' && conf[jj] != ')') jj++;
    calls[idx].push_back(conf.substr(ii, jj - ii));
    jj++;
    ii = jj;
  }
}
bool equal(int i, int j) {
  if (calls[i][0] != procedure[j][0]) return false;
  if (calls[i].size() != procedure[j].size()) return false;
  for (int k = 1; k < (int)calls[i].size(); k++) {
    if (procedure[j][k] != "T" && m[calls[i][k]] != procedure[j][k])
      return false;
  }
  return true;
}
int main() {
  scanf("%d\n", &N);
  for (int i = 0; i < N; i++) {
    gets(line);
    n_line = trim(line);
    decode(n_line, i);
  }
  scanf("%d\n", &M);
  for (int i = 0; i < M; i++) {
    scanf("%s %s\n", type, name);
    m[(string)name] = (string)type;
  }
  scanf("%d\n", &K);
  for (int i = 0; i < K; i++) {
    gets(line);
    n_line = trim(line);
    decode2(n_line, i);
  }
  for (int i = 0; i < K; i++) {
    int ans = 0;
    for (int j = 0; j < N; j++)
      if (equal(i, j)) {
        ans++;
      }
    printf("%d\n", ans);
  }
}
