#include <bits/stdc++.h>
using namespace std;
struct Z {
  string name;
  vector<string> par;
};
Z V[1005];
void process(string str, int ind) {
  string s;
  stringstream ss;
  ss << str;
  ss >> s;
  V[ind].name = s;
  ss >> s;
  V[ind].name = s;
  while (ss >> s) {
    V[ind].par.push_back(s);
  }
}
map<string, string> M;
int N;
void process1(string str, int ind) {
  string s, s2;
  stringstream ss;
  ss << str;
  ss >> s;
  ss >> s2;
  M[s2] = s;
}
void process2(string str) {
  string s, s2;
  vector<string> v;
  stringstream ss;
  ss << str;
  ss >> s2;
  while (ss >> s) {
    v.push_back(M[s]);
  }
  bool state;
  int cn = 0;
  for (int i = 0; i < N; i++) {
    state = true;
    if (V[i].name != s2) continue;
    if (V[i].par.size() == v.size()) {
      for (int j = 0; j < v.size(); j++) {
        if (V[i].par[j] == "T")
          ;
        else if (V[i].par[j] != v[j])
          state = false;
      }
      if (state) cn++;
    }
  }
  cout << cn << endl;
}
int main() {
  int i, j, k, n, m;
  string str;
  cin >> n;
  cin.ignore();
  for (i = 0; i < n; i++) {
    getline(cin, str);
    for (j = str.length() - 1; j >= 0; j--) {
      if (!isalpha(str[j]) && !isdigit(str[j])) str[j] = ' ';
    }
    process(str, i);
  }
  N = n;
  cin >> n;
  cin.ignore();
  for (i = 0; i < n; i++) {
    getline(cin, str);
    for (j = str.length() - 1; j >= 0; j--) {
      if (!isalpha(str[j]) && !isdigit(str[j])) str[j] = ' ';
    }
    process1(str, i);
  }
  cin >> n;
  cin.ignore();
  for (i = 0; i < n; i++) {
    getline(cin, str);
    for (j = str.length() - 1; j >= 0; j--) {
      if (!isalpha(str[j]) && !isdigit(str[j])) str[j] = ' ';
    }
    process2(str);
  }
}
