#include <bits/stdc++.h>
using namespace std;
map<string, string> types;
map<string, vector<vector<string> > > templates;
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    string g;
    cin >> g;
    g = "";
    getline(cin, g);
    string name;
    int k = 0;
    string tmp;
    for (; k < g.size(); k++) {
      if (g[k] == '(') {
        name = tmp;
        break;
      }
      if (g[k] != ' ') tmp += g[k];
    }
    tmp = "";
    vector<string> types;
    for (; k < g.size(); k++) {
      if (g[k] == ')') {
        types.push_back(tmp);
        templates[name].push_back(types);
      } else if (g[k] == ',') {
        types.push_back(tmp);
        tmp = "";
      } else if (g[k] != ' ' && g[k] != '(')
        tmp += g[k];
    }
  }
  int m;
  cin >> m;
  for (int i = 0; i < m; i++) {
    string g, k;
    cin >> g >> k;
    types[k] = g;
  }
  int u;
  cin >> u;
  string tmp;
  getline(cin, tmp);
  for (int i = 0; i < u; i++) {
    string g;
    getline(cin, g);
    int k = 0;
    string tmp;
    string name;
    for (; k < g.size(); k++) {
      if (g[k] == '(') {
        name = tmp;
        break;
      }
      if (g[k] != ' ') tmp += g[k];
    }
    tmp = "";
    vector<string> type1;
    for (; k < g.size(); k++) {
      if (g[k] == ')') {
        type1.push_back(types[tmp]);
      } else if (g[k] == ',') {
        type1.push_back(types[tmp]);
        tmp = "";
      } else if (g[k] != ' ' && g[k] != '(')
        tmp += g[k];
    }
    int nums = 0;
    for (int i = 0; i < templates[name].size(); i++) {
      bool used = false;
      string myType;
      bool is = true;
      if (templates[name][i].size() != type1.size()) continue;
      for (int j = 0; j < templates[name][i].size(); j++) {
        if (templates[name][i][j] != "T" && templates[name][i][j] != type1[j]) {
          is = false;
          break;
        }
      }
      nums += is;
    }
    cout << nums << "\n";
  }
}
