#include <bits/stdc++.h>
using namespace std;

typedef pair<int, double> PID;

const int MAXR = 300 + 10, MAXN = 500 + 10;
const double inf = 1e9;

map<string, int> ID;
vector<string> color;
map<int, double> dp[MAXN][MAXN];
int rule[MAXR][MAXR];
int R, N, M;

inline int getID(string s) {
    if (ID.count(s)) return ID[s];
    ID[s] = color.size(); color.push_back(s);
    return color.size() - 1;
}

int main() {
    int cas = 0;
    while (cin >> R) {
        if (cas) cout << endl; ++ cas;
        ID.clear(); color.clear();
        memset(rule, -1, sizeof(rule));
        for (int i = 0; i < R; ++ i) {
            char c1[100], c2[100], c3[100];
            scanf("%s%s%s", c1, c2, c3);
            int i1 = getID(c1), i2 = getID(c2), i3 = getID(c3);
            rule[i1][i2] = rule[i2][i1] = i3;
        }
        int T; scanf("%d", &T);
        while (T --) {
            scanf("%d", &N);
            for (int i = 0; i < N; ++ i) {
                for (int j = 0; j < N; ++ j) {
                    dp[i][j].clear();
                }
            }
            for (int i = 0; i < N; ++ i) {
                for (char c[100]; scanf("%s", c) && strcmp(c, "END") != 0;) {
                    double p; scanf("%lf", &p);
                    dp[i][i][getID(c)] = log(p);
                }
            }
            for (int step = 1; step < N; ++ step) {
                for (int i = 0; i < N - step; ++ i) {
                    for (int j = 0; j < step; ++ j) {
                        for (auto &left : dp[i][i + j]) {
                            for (auto &right : dp[i + j + 1][i + step]) {
                                int gen = rule[left.first][right.first];
                                if (gen == -1) continue;
                                double prob = left.second + right.second;
                                if (!dp[i][i + step].count(gen)) dp[i][i + step][gen] = prob;
                                else dp[i][i + step][gen] = max(dp[i][i + step][gen], prob);
                            }
                        }
                    }
                }
            }
            if (dp[0][N - 1].empty()) cout << "GAMEOVER" << endl;
            else {
                int ret = 0; double prob = -inf;
                for (auto &x : dp[0][N - 1]) {
                    if (x.second > prob) prob = x.second, ret = x.first;
                }
                cout << color[ret] << endl;
            }
        }
    }
    return 0;
}
