#include <bits/stdc++.h>
using namespace std;
map<string, vector<vector<string> > > mp;
map<string, string> type;
char s[1000010];
int len;
int space(int st) {
  for (int i = st; i < len; i++)
    if (s[i] != ' ') return i;
  return len;
}
vector<string> l;
void get_vector(int pos) {
  l.clear();
  pos++;
  while (1) {
    pos = space(pos);
    string f = "";
    while (1) {
      if (s[pos] == ' ' || s[pos] == ',' || s[pos] == ')') break;
      f += s[pos++];
    }
    l.push_back(f);
    pos = space(pos);
    if (s[pos] == ')') break;
    pos++;
  }
}
int n;
string f;
void build() {
  scanf("%d", &n);
  gets(s);
  while (n--) {
    gets(s);
    len = strlen(s);
    int pos = 0;
    pos = space(pos);
    pos += 4;
    pos = space(pos);
    f = "";
    while (pos < len) {
      if (s[pos] == '(' || s[pos] == ' ') break;
      f += s[pos++];
    }
    pos = space(pos);
    get_vector(pos);
    mp[f].push_back(l);
  }
}
int main() {
  mp.clear();
  build();
  scanf("%d", &n);
  type.clear();
  string a, b;
  while (n--) {
    cin >> a >> b;
    type[b] = a;
  }
  scanf("%d", &n);
  gets(s);
  while (n--) {
    gets(s);
    len = strlen(s);
    int pos = 0;
    pos = space(pos);
    f = "";
    while (pos < len) {
      if (s[pos] == '(' || s[pos] == ' ') break;
      f += s[pos++];
    }
    pos = space(pos);
    get_vector(pos);
    if (mp.find(f) == mp.end())
      printf("0\n");
    else {
      int ans = 0;
      int ll = mp[f].size();
      for (int k = 0; k < ll; k++) {
        bool flag = true;
        int lenl = l.size();
        int lenh = mp[f][k].size();
        if (lenl != lenh) continue;
        for (int i = 0; i < lenl; i++) {
          if (type.find(l[i]) == type.end()) flag = false;
          if (mp[f][k][i] == "T") continue;
          if (type[l[i]] != mp[f][k][i]) flag = false;
        }
        if (flag) ans++;
      }
      printf("%d\n", ans);
    }
  }
  return 0;
}
