#include <bits/stdc++.h>
using namespace std;
const int pi = acos(-1.0);
const int N = 200000 + 3;
char s[N];
string pro[N][9];
string nowst[9];
int num[N];
int nums;
map<string, string> str_change;
int main() {
  int n, m, T;
  scanf("%d", &n);
  gets(s);
  for (int i = 1; i <= n; i++) {
    gets(s);
    int len = strlen(s);
    int j;
    for (j = 0; j < len; j++)
      if (s[j] == ',') num[i]++;
    num[i]++;
    string tmp = "";
    for (j = 0; j < len; j++)
      if (s[j] != ' ') tmp += s[j];
    j = 4;
    string stname = "";
    while (tmp[j] != '(') stname += tmp[j++];
    pro[i][0] = stname;
    j++;
    for (int p = 1; p <= num[i]; p++) {
      string sttmp = "";
      while (tmp[j] != ',' && tmp[j] != ')') sttmp += tmp[j++];
      j++;
      pro[i][p] = sttmp;
    }
  }
  scanf("%d", &m);
  for (int i = 1; i <= m; i++) {
    string x, y;
    cin >> x >> y;
    str_change[y] = x;
  }
  scanf("%d", &T);
  gets(s);
  for (int i = 1; i <= T; i++) {
    gets(s);
    int len = strlen(s);
    int j;
    nums = 0;
    for (j = 0; j < len; j++)
      if (s[j] == ',') nums++;
    nums++;
    string tmp = "";
    for (j = 0; j < len; j++)
      if (s[j] != ' ') tmp += s[j];
    string stname = "";
    j = 0;
    while (tmp[j] != '(') stname += tmp[j++];
    nowst[0] = stname;
    j++;
    for (int p = 1; p <= nums; p++) {
      string sttmp = "";
      while (tmp[j] != ',' && tmp[j] != ')') sttmp += tmp[j++];
      j++;
      nowst[p] = sttmp;
    }
    int res = 0;
    for (int q = 1; q <= n; q++)
      if (nums == num[q] && pro[q][0] == nowst[0]) {
        bool flag = true;
        for (int qq = 1; qq <= num[q]; qq++)
          if (!(pro[q][qq] == "T" || pro[q][qq] == str_change[nowst[qq]]))
            flag = false;
        if (flag) res++;
      }
    printf("%d\n", res);
  }
  return 0;
}
