#include <bits/stdc++.h>
using namespace std;
struct MyMap {
  map<string, int> mp;
  int operator[](string &s) {
    if (mp.find(s) == mp.end()) {
      int sz = mp.size();
      mp[s] = sz;
    }
    return mp[s];
  }
} f2i, t2i, v2i;
int n;
char s[100000];
set<vector<int> > func;
int main() {
  t2i.mp["T"] = 0;
  gets(s), sscanf(s, "%d", &n);
  while (n--) {
    gets(s);
    for (int i = 0; s[i]; i++) {
      if (s[i] == '(' || s[i] == ')' || s[i] == ',') {
        s[i] = ' ';
      }
    }
    istringstream sin(s);
    vector<int> v;
    string t;
    sin >> t;
    sin >> t;
    v.push_back(f2i[t]);
    while (sin >> t) v.push_back(t2i[t]);
    func.insert(v);
  }
  gets(s), sscanf(s, "%d", &n);
  while (n--) {
    gets(s);
    string a, b;
    istringstream sin(s);
    string t;
    sin >> a >> b;
    v2i.mp[b] = t2i[a];
  }
  gets(s), sscanf(s, "%d", &n);
  while (n--) {
    gets(s);
    for (int i = 0; s[i]; i++) {
      if (s[i] == '(' || s[i] == ')' || s[i] == ',') {
        s[i] = ' ';
      }
    }
    istringstream sin(s);
    vector<int> v;
    string t;
    sin >> t;
    v.push_back(f2i[t]);
    while (sin >> t) v.push_back(v2i[t]);
    int m = v.size() - 1;
    int cnt = 0;
    for (int b = (0); b < (int)(1 << m); b++) {
      bool f = true;
      vector<int> v2 = v;
      for (int k = (0); k < (int)(m); k++) {
        if ((b >> k) & 1) {
          v2[k + 1] = 0;
        }
      }
      if (f) cnt += (func.find(v2) != func.end());
    }
    printf("%d\n", cnt);
  }
  return 0;
}
