/* -*- coding: utf-8 -*- * * 1780.cc: No.1780 [Cherry Anniversary] 真冬に咲く26の櫻の木 - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 200000; const int M = 16; const int L = 26; const long long LINF = 1LL << 60; /* typedef */ typedef long long ll; typedef ll mat[M][M]; /* global variables */ int cs[L], ks[L]; int bits[MAX_N], as[MAX_N], bs[MAX_N], es[MAX_N]; mat ma, mb; ll mds[L][M]; /* subroutines */ inline void unitmat(mat a) { for (int i = 0; i < M; i++) { fill(a[i], a[i] + M, -LINF); a[i][i] = 0; } } inline void copymat(const mat a, mat b) { memcpy(b, a, sizeof(mat)); } inline void mulmat(const mat a, const mat b, mat c) { unitmat(c); for (int k = 0; k < M; k++) for (int i = 0; i < M; i++) for (int j = 0; j < M; j++) if (a[i][k] > -LINF && b[k][j] > -LINF) c[i][j] = max(c[i][j], a[i][k] + b[k][j]); } inline void powmat(const mat a, int b, mat c) { mat s, t; copymat(a, s); unitmat(c); while (b > 0) { if (b & 1) { mulmat(c, s, t); copymat(t, c); } mulmat(s, s, t); copymat(t, s); b >>= 1; } } /* main */ int main() { for (int i = 0; i < L; i++) scanf("%d", cs + i), cs[i]--; for (int i = 0; i < L; i++) scanf("%d", ks + i); int n; scanf("%d", &n); for (int i = 0; i < n; i++) { char s[32]; scanf("%s%d%d%d", s, as + i, bs + i, es + i); as[i]--, bs[i]--; for (int j = 0; s[j]; j++) bits[i] |= (1 << (s[j] - 'A')); } for (int i = 0, bi = 1; i < L; i++, bi <<= 1) { unitmat(ma); for (int j = 0; j < n; j++) if ((bits[j] & bi) && ma[as[j]][bs[j]] < es[j]) ma[as[j]][bs[j]] = ma[bs[j]][as[j]] = es[j]; powmat(ma, ks[i], mb); for (int j = 0; j < M; j++) mds[i][j] = mb[cs[i]][j]; } ll maxsum = -LINF; for (int c = 0; c < M; c++) { //printf("c=%d\n", c); //for (int i = 0; i < L; i++) printf(" %lld", mds[i][c]); putchar('\n'); ll sum = 0; for (int i = 0; i < L; i++) { if (mds[i][c] <= -LINF) { sum = -LINF; break; } sum += mds[i][c]; } maxsum = max(maxsum, sum); } if (maxsum <= -LINF) puts("Impossible"); else printf("%lld\n", maxsum); return 0; }