#include <bits/stdc++.h>
using namespace std;
set<string> Fun;
map<string, string> Typ;
int F;
int main() {
  scanf("%d ", &F);
  for (int i = 0; i < (F); ++i) {
    char line[147];
    cin.getline(line, 147);
    char* pch;
    string fname;
    string params;
    pch = strtok(line, " (),");
    if (pch == NULL) continue;
    pch = strtok(NULL, " (),");
    if (pch == NULL) continue;
    fname = pch;
    fname += "!";
    while (pch != NULL) {
      pch = strtok(NULL, " (),");
      if (pch == NULL) break;
      fname += " ";
      fname += pch;
    }
    Fun.insert(fname);
  }
  scanf("%d ", &F);
  char s1[147], s2[147];
  for (int i = 0; i < (F); ++i) {
    scanf("%s %s ", s1, s2);
    Typ[s2] = s1;
  }
  scanf("%d ", &F);
  for (int i = 0; i < (F); ++i) {
    char line[147];
    cin.getline(line, 147);
    char* pch;
    string fname[47];
    pch = strtok(line, " (),");
    if (pch == NULL) continue;
    for (int k = 0; k < (47); ++k) {
      fname[k] = pch;
      fname[k] += "!";
    }
    int poc = 1;
    while (pch != NULL) {
      pch = strtok(NULL, " (),");
      if (pch == NULL) break;
      for (int k = 0; k < (47); ++k) {
        fname[k] += " ";
        if (k & poc)
          fname[k] += Typ[pch];
        else
          fname[k] += "T";
      }
      poc *= 2;
    }
    int pocet = 0;
    for (int k = 0; k < (poc); ++k) pocet += Fun.count(fname[k]);
    printf("%d\n", pocet);
  }
}
