#include <bits/stdc++.h>
using namespace std;
char buf[110];
string input() {
  gets(buf);
  string s = buf;
  return s;
}
int input_int() {
  string s = input();
  return atoi(s.c_str());
}
vector<string> parsed_input() {
  string s = input();
  int i;
  for (i = 0; i < s.length(); 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;
  int i;
  for (i = 0; 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, i, j;
  N = input_int();
  for (i = 0; i < N; i++) {
    vector<string> v = parsed_input();
    name[i] = v[1];
    for (j = 2; j < v.size(); j++) types[i].push_back(v[j]);
  }
  V = input_int();
  for (i = 0; i < V; i++) {
    vector<string> v = parsed_input();
    mp[v[1]] = v[0];
  }
  Q = input_int();
  for (i = 0; i < Q; i++) {
    vector<string> v = parsed_input();
    int ans = 0;
    for (j = 0; j < N; j++)
      if (check(j, v)) ans++;
    cout << ans << endl;
  }
  return 0;
}
