#include <bits/stdc++.h>
using namespace std;
const int MAX = 100 * 1000;
const int INF = 1 << 29;
const long long D = 1000 * 1000 * 1000 + 7;
const string T = "T";
int n, m, k;
map<string, vector<vector<int> > > func;
map<string, int> type;
map<string, int> var;
void add(string s) {
  if (type[s] == 0 && s != T) type[s] = type.size() - 1;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n;
  add(T);
  stringstream ss(stringstream::in | stringstream::out);
  ss.clear();
  string s;
  for (int i = 0; i < n; i++) {
    cin >> s;
    getline(cin, s);
    for (int i = 0; i < (int)s.size(); i++)
      if (s[i] == ')' || s[i] == '(' || s[i] == ',') s[i] = ' ';
    ss << s;
    string name;
    ss >> name;
    vector<int> a;
    while (ss >> s) {
      add(s);
      a.push_back(type[s]);
    }
    ss.clear();
    func[name].push_back(a);
  }
  cin >> m;
  for (int i = 0; i < m; i++) {
    cin >> s;
    int a = type[s];
    cin >> s;
    var[s] = a;
  }
  cin >> k;
  getline(cin, s);
  for (int i = 0; i < k; i++) {
    ss.clear();
    getline(cin, s);
    for (int i = 0; i < (int)s.size(); i++)
      if (s[i] == ')' || s[i] == '(' || s[i] == ',') s[i] = ' ';
    ss << s;
    string name;
    ss >> name;
    vector<int> a;
    while (ss >> s) a.push_back(var[s]);
    if (func.find(name) == func.end()) {
      cout << 0 << endl;
      continue;
    }
    int cnt = 0;
    vector<vector<int> > b = func[name];
    for (int i = 0; i < (int)b.size(); i++) {
      bool f = true;
      if (a.size() != b[i].size()) continue;
      for (int j = 0; j < (int)a.size() && f; j++)
        if (b[i][j] != a[j] && b[i][j] != 0) f = false;
      if (f) cnt++;
    }
    cout << cnt << endl;
  }
  return 0;
}
