#include <bits/stdc++.h>
using namespace std;
struct proc {
  string name;
  vector<string> args;
  bool fit(proc& p) {
    if (name != p.name) return false;
    if (args.size() != p.args.size()) return false;
    for (int i = 0; i < args.size(); i++) {
      if (p.args[i] == "T") continue;
      if (args[i] != p.args[i]) return false;
    }
    return true;
  }
};
char buf[105];
proc read(bool a) {
  proc p;
  if (a) scanf(" void");
  scanf(" %[a-z0-9] (", &buf);
  p.name = buf;
  while (scanf(" %[Ta-z0-9]", &buf) == 1) {
    p.args.push_back(buf);
    scanf(" ,");
  }
  scanf(" )");
  return p;
}
map<string, string> mp;
int main() {
  int n;
  cin >> n;
  vector<proc> vp(n);
  for (int i = 0; i < n; i++) vp[i] = read(true);
  int m;
  cin >> m;
  for (int i = 0; i < m; i++) {
    string a, b;
    cin >> a >> b;
    mp[b] = a;
  }
  int k;
  cin >> k;
  while (k--) {
    proc p = read(false);
    for (int i = 0; i < p.args.size(); i++) p.args[i] = mp[p.args[i]];
    int ans = 0;
    for (int i = 0; i < n; i++)
      if (p.fit(vp[i])) ans++;
    cout << ans << endl;
  }
  return 0;
}
