#include void chmax(int* a, int b) { if (*a < b) *a = b; } void chmaxll(long long* a, long long b) { if (*a < b) *a = b; } int main() { const int inf = -(1 << 30); int i, j, k, l, u, w, C[26], K[26], N, A, B, E, adj[26][17][17]; char S[31]; for (i = 0; i < 26; i++) scanf("%d", &(C[i])); for (i = 0; i < 26; i++) scanf("%d", &(K[i])); for (i = 0; i < 26; i++) for (u = 1; u <= 16; u++) for (w = 1; w <= 16; w++) adj[i][u][w] = inf; scanf("%d", &N); for (i = 1; i <= N; i++) { scanf("%s %d %d %d", S, &A, &B, &E); for (j = 0; S[j] != 0; j++) { chmax(&(adj[S[j] - 'A'][A][B]), E); chmax(&(adj[S[j] - 'A'][B][A]), E); } } const long long infll = -(1LL << 60); long long ans = infll, dp[26][101][17], tmp, sum; for (i = 0; i < 26; i++) { for (j = 0; j <= 100; j++) { for (k = 1; k <= 16; k++) dp[i][j][k] = infll; } dp[i][0][C[i]] = 0; for (j = 0; j < 100; j++) { for (k = 1; k <= 16; k++) { for (u = k, w = 1; w <= 16; w++) { if (adj[i][u][w] != inf) chmaxll(&(dp[i][j+1][w]), dp[i][j][u] + adj[i][u][w]); } } } } for (k = 1; k <= 16; k++) { for (i = 0, sum = 0; i < 26; i++) { for (j = 0, tmp = infll; j <= 100 && j <= K[i]; j++) chmaxll(&tmp, dp[i][j][k]); if (K[i] > 100) { for (j = 16; j >= 2; j--) { for (l = 100; l >= 50; l--) if (dp[i][l][k] - dp[i][l-1][k] != dp[i][l-j][k] - dp[i][l-j-1][k]) break; if (l < 50) break; } if (j < 2) return -1; for (l = 100 - j + 1; l <= 100; l++) chmaxll(&tmp, (dp[i][l][k] - dp[i][l-j][k]) * ((K[i] - l) / j) + dp[i][l][k]); } if (tmp == infll) break; sum += tmp; } if (i == 26) chmaxll(&ans, sum); } if (ans == infll) printf("Impossible\n"); else printf("%lld\n", ans); fflush(stdout); return 0; }