#include <bits/stdc++.h>
using namespace std;
map<string, string> mymap;
char func[1005][1005], argu[1005][5][1005];
int av[1005];
int main() {
  int i, j;
  int n, m, l, k, f;
  cin >> n;
  char str[1005], tmp[1000];
  int pos = 0;
  for (i = 0; i < n; i++) {
    cin >> tmp;
    k = 0;
    f = 0;
    scanf(" %[^\n]s", str);
    for (j = 0; str[j] != 0; j++) {
      if (str[j] == ' ') continue;
      if (str[j] == '(') {
        func[i][k] = 0;
        k = 0;
        f = 1;
        pos = 0;
        l = 0;
        continue;
      }
      if (str[j] == ')') {
        argu[i][pos][l] = 0;
        av[i] = pos;
        break;
      }
      if (str[j] == ',') {
        argu[i][pos][l] = 0;
        pos++;
        l = 0;
        continue;
      }
      if (f == 0)
        func[i][k++] = str[j];
      else
        argu[i][pos][l++] = str[j];
    }
  }
  int z;
  cin >> z;
  string s1, s2;
  for (i = 0; i < z; i++) {
    cin >> s1 >> s2;
    mymap[s2] = s1;
  }
  cin >> m;
  for (i = 0; i < m; i++) {
    char fn[10000];
    string st[5];
    int c = 0;
    k = l = pos = f = 0;
    scanf(" %[^\n]s", str);
    for (j = 0; str[j] != 0; j++) {
      if (str[j] == ' ') continue;
      if (str[j] == '(') {
        fn[k] = 0;
        k = 0;
        f = 1;
        pos = 0;
        continue;
      }
      if (str[j] == ')') {
        c = pos;
        break;
      }
      if (str[j] == ',') {
        pos++;
        continue;
      }
      if (f == 0)
        fn[k++] = str[j];
      else
        st[pos] += str[j];
    }
    int ans = 0;
    for (j = 0; j < n; j++) {
      if (strcmp(fn, func[j]) == 0) {
        if (av[j] == c) {
          int fl = 0;
          for (k = 0; k <= c; k++) {
            string dum = mymap[st[k]];
            char lol[1000];
            for (z = 0; z < dum.size(); z++) lol[z] = dum[z];
            lol[z] = 0;
            dum.erase();
            if (strcmp(lol, argu[j][k]) != 0) {
              if (strcmp(argu[j][k], "T") != 0) {
                fl = 1;
                break;
              }
            }
          }
          if (fl == 0) ans++;
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
