#include <bits/stdc++.h>
using namespace std;
int n, m, q;
struct templateItem {
  int count;
  vector<int> types;
  templateItem() : count(0), types() {}
};
vector<templateItem> tem[1001];
map<string, int> db;
map<string, int> tt;
map<string, int> vardb;
int fc(0);
char buff[100000], buff2[100000], buff3[100000], name[100000], typebuf[1000];
int vars[1001];
int main() {
  scanf("%d\n", &n);
  tt["T"] = 0;
  tt["int"] = 1;
  tt["double"] = 2;
  tt["string"] = 3;
  for (int i = 1; i <= n; ++i) {
    gets(buff);
    strcpy(buff2, buff);
    char *pos = strchr(buff2, '(');
    *pos = 0;
    char *pos2 = strstr(buff2, "void");
    pos2 += 4;
    sscanf(pos2, "%s", name);
    string tempName(name);
    if (!db.count(tempName)) db[tempName] = ++fc;
    int fid = db[tempName];
    ++pos;
    strcpy(buff3, pos);
    pos = strchr(buff3, ')');
    *pos = 0;
    templateItem tempItem;
    char *token = strtok(buff3, ",");
    while (token) {
      tempItem.count++;
      sscanf(token, "%s", typebuf);
      tempItem.types.push_back(tt[typebuf]);
      token = strtok(NULL, ",");
    }
    tem[fid].push_back(tempItem);
  }
  scanf("%d\n", &m);
  for (int i = 1; i <= m; ++i) {
    gets(buff);
    sscanf(buff, "%s %s", buff2, buff3);
    vars[i] = tt[buff2];
    vardb[buff3] = i;
  }
  scanf("%d\n", &q);
  for (int i = 1; i <= q; ++i) {
    gets(buff);
    strcpy(buff2, buff);
    char *pos = strchr(buff2, '(');
    *pos = 0;
    sscanf(buff2, "%s", name);
    if (!db.count(name)) {
      printf("0\n");
      continue;
    }
    ++pos;
    strcpy(buff3, pos);
    pos = strchr(buff3, ')');
    *pos = 0;
    char *token = strtok(buff3, ",");
    templateItem tempItem;
    while (token) {
      tempItem.count++;
      sscanf(token, "%s", typebuf);
      int varid = vardb[typebuf];
      tempItem.types.push_back(vars[varid]);
      token = strtok(NULL, ",");
    }
    vector<templateItem> &a(tem[db[name]]);
    int ans = 0;
    for (vector<templateItem>::iterator it = a.begin(); it != a.end(); ++it) {
      bool matched(true);
      if (it->count != tempItem.count) continue;
      for (int j = 0; j != it->count; ++j)
        if (it->types[j] != tempItem.types[j] && (it->types[j])) {
          matched = false;
          break;
        }
      if (matched) ++ans;
    }
    printf("%d\n", ans);
  }
  return 0;
}
