#include <bits/stdc++.h>
using namespace std;
char c[110];
int string_to_int(string s) {
  int res = 0;
  for (int i = 0, _n = s.size(); i < s.size(); i++) {
    res *= 10;
    res += s[i] - '0';
  }
  return res;
}
string insert() {
  gets(c);
  string s = c;
  return s;
}
int input_to_int() {
  string s = insert();
  return string_to_int(s);
}
vector<string> par_input() {
  string s = insert();
  int i;
  for (int i = 0, _n = s.size(); i < s.size(); i++)
    if (s[i] == '(' || s[i] == ')' || s[i] == ',') s[i] = ' ';
  istringstream ss(s);
  vector<string> ans;
  while (ss >> s) ans.push_back(s);
  return ans;
}
string name[1010];
vector<string> types[1010];
map<string, string> mp;
bool check(int id, vector<string>& v) {
  if (v.size() != types[id].size() + 1) return false;
  if (name[id] != v[0]) return false;
  for (int i = 0, _n = types[id].size(); i < types[id].size(); i++)
    if (types[id][i] != "T" && mp[v[i + 1]] != types[id][i]) return false;
  return true;
}
int main() {
  int n, v, q;
  n = input_to_int();
  for (int i = 0, _n = n; i < n; i++) {
    vector<string> v = par_input();
    name[i] = v[1];
    for (int j = 2; j < v.size(); j++) types[i].push_back(v[j]);
  }
  v = input_to_int();
  for (int i = 0, _n = v; i < v; i++) {
    vector<string> v = par_input();
    mp[v[1]] = v[0];
  }
  q = input_to_int();
  for (int i = 0, _n = q; i < q; i++) {
    vector<string> v = par_input();
    int res = 0;
    for (int j = 0, _n = n; j < n; j++)
      if (check(j, v)) res++;
    cout << res << endl;
  }
  return 0;
}
