#include <bits/stdc++.h>
using namespace std;
inline bool val(const char &c) {
  return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == 'T');
}
bool comp(const vector<string> &a, const vector<string> &b) {
  return a.size() < b.size();
}
int main() {
  map<string, vector<vector<string> > > f;
  map<string, vector<vector<string> > >::iterator it;
  map<string, string> v;
  map<string, string>::iterator jt;
  string a, b, c;
  int k, n, i, j;
  getline(cin, a);
  sscanf(a.c_str(), "%d", &k);
  while (k--) {
    getline(cin, a);
    for (i = 0; a[i] == ' '; i++)
      ;
    j = i;
    for (; a[i] != ' '; i++)
      ;
    b = a.substr(j, i - j);
    for (; a[i] == ' '; i++)
      ;
    j = i;
    for (; val(a[i]); i++)
      ;
    c = b = a.substr(j, i - j);
    for (; a[i] != '('; i++)
      ;
    i++;
    vector<string> t;
    for (; 1;) {
      for (; a[i] == ' '; i++)
        ;
      j = i;
      for (; val(a[i]); i++)
        ;
      b = a.substr(j, i - j);
      t.push_back(b);
      for (; a[i] == ' '; i++)
        ;
      if (a[i] == ')')
        break;
      else
        i++;
    }
    f[c].push_back(t);
  }
  for (it = f.begin(); it != f.end(); it++)
    sort(it->second.begin(), it->second.end(), comp);
  getline(cin, a);
  sscanf(a.c_str(), "%d", &k);
  while (k--) {
    getline(cin, a);
    for (i = 0; a[i] == ' '; i++)
      ;
    j = i;
    for (; a[i] != ' '; i++)
      ;
    b = a.substr(j, i - j);
    for (; a[i] == ' '; i++)
      ;
    j = i;
    for (; val(a[i]); i++)
      ;
    c = a.substr(j, i - j);
    v[c] = b;
  }
  getline(cin, a);
  sscanf(a.c_str(), "%d", &k);
  while (k--) {
    getline(cin, a);
    n = 0;
    for (i = 0; a[i] == ' '; i++)
      ;
    j = i;
    for (; val(a[i]); i++)
      ;
    b = a.substr(j, i - j);
    if ((it = f.find(b)) != f.end()) {
      c = b;
      for (; a[i] != '('; i++)
        ;
      i++;
      vector<string> t;
      for (; 1;) {
        for (; a[i] == ' '; i++)
          ;
        j = i;
        for (; val(a[i]); i++)
          ;
        b = a.substr(j, i - j);
        t.push_back(b);
        for (; a[i] == ' '; i++)
          ;
        if (a[i] == ')')
          break;
        else
          i++;
      }
      while (it != f.end() && it->first == c) {
        int I = lower_bound(it->second.begin(), it->second.end(), t, comp) -
                it->second.begin();
        while (I < it->second.size() && it->second[I].size() == t.size()) {
          bool sw = 1;
          for (int u = 0; sw && u < t.size(); u++) {
            if (it->second[I][u] != "T") {
              if (v[t[u]] != it->second[I][u]) sw = 0;
            }
          }
          if (sw) n++;
          I++;
        }
        it++;
      }
    }
    printf("%d\n", n);
  }
  return 0;
}
