#include <bits/stdc++.h>
using namespace std;
const int N = int(2000);
int n, m, k;
string second;
int a[N][10], b[20], bn, sz[N], an;
int aa, bb, cc, xx;
string name[N], t;
map<string, string> M;
int main() {
  scanf("%d\n", &n);
  for (int i = 1; i <= n; i++) {
    getline(cin, second);
    int j = 0;
    for (j = 0; j < second.size(); j++) {
      if (second[j] == 'v' && second[j + 1] == 'o' && second[j + 2] == 'i' &&
          second[j + 3] == 'd') {
        j += 4;
        break;
      }
    }
    while (second[j] == ' ') j++;
    t = "";
    while (second[j] != ' ' && second[j] != '(') {
      t += second[j];
      j++;
    }
    name[i] = t;
    while (second[j] != '(') j++;
    j++;
    t = "";
    an = 0;
    while (second[j] != ')') {
      if (second[j] == ',') {
        if (t[0] == 'i') a[i][++an] = 1;
        if (t[0] == 'd') a[i][++an] = 2;
        if (t[0] == 's') a[i][++an] = 3;
        if (t[0] == 'T') a[i][++an] = 4;
        t = "";
      } else {
        if (second[j] != ' ') {
          t += second[j];
        }
      }
      j++;
    }
    if (t[0] == 'i') a[i][++an] = 1;
    if (t[0] == 'd') a[i][++an] = 2;
    if (t[0] == 's') a[i][++an] = 3;
    if (t[0] == 'T') a[i][++an] = 4;
    sz[i] = an;
  }
  scanf("%d\n", &k);
  for (int i = 1; i <= k; i++) {
    cin >> second >> t;
    M[t] = second;
  }
  scanf("%d\n", &m);
  string ss, nm;
  for (int i = 1; i <= m; i++) {
    int j = 0;
    int res = 0;
    getline(cin, second);
    aa = bb = cc = 0;
    while (second[j] == ' ') j++;
    t = "";
    while (second[j] != ' ' && second[j] != '(') {
      t += second[j];
      j++;
    }
    while (second[j] != '(') j++;
    j++;
    nm = t;
    t = "";
    an = 0;
    while (second[j] != ')') {
      if (second[j] == ',') {
        t = M[t];
        if (t[0] == 'i') b[++an] = 1;
        if (t[0] == 'd') b[++an] = 2;
        if (t[0] == 's') b[++an] = 3;
        t = "";
      } else {
        if (second[j] != ' ') {
          t += second[j];
        }
      }
      j++;
    }
    t = M[t];
    if (t[0] == 'i') b[++an] = 1;
    if (t[0] == 'd') b[++an] = 2;
    if (t[0] == 's') b[++an] = 3;
    bool ok = 1;
    for (int k = 1; k <= n; k++)
      if (sz[k] == an && nm == name[k]) {
        ok = 1;
        for (int l = 1; l <= an; l++) {
          if (a[k][l] != b[l] && a[k][l] != 4) ok = 0;
        }
        if (ok) res++;
      }
    printf("%d\n", res);
  }
  return 0;
}
