#include <bits/stdc++.h>
using namespace std;
const int maxn = 1001;
char f[maxn][102], g[maxn][6][102];
char vtype[maxn][102], vname[maxn][102];
char ff[102], gg[6][102];
int a[maxn];
int n, m, k;
int main() {
  int i, j, p, s;
  char c;
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%s", ff);
    scanf(" %[a-z0-9]s", f[i]);
    while (scanf(" %c", &c) && c != ')') scanf(" %[Ta-z0-9]s", g[i][a[i]++]);
  }
  scanf("%d", &m);
  for (i = 0; i < m; i++) scanf("%s%s", vtype[i], vname[i]);
  scanf("%d", &k);
  while (k--) {
    scanf(" %[a-z0-9]s", ff);
    j = 0;
    while (scanf(" %c", &c) && c != ')') {
      scanf(" %[Ta-z0-9]s", gg[j]);
      for (i = 0; strcmp(vname[i], gg[j]); i++)
        ;
      strcpy(gg[j], vtype[i]);
      j++;
    }
    s = 0;
    for (i = 0; i < n; i++)
      if (!strcmp(f[i], ff) && a[i] == j) {
        for (p = 0; p < j; p++)
          if (strcmp(g[i][p], "T") && strcmp(g[i][p], gg[p])) p = j + 1;
        if (p == j) s++;
      }
    printf("%d\n", s);
  }
  return 0;
}
