#ifdef MAIN bool __multi__ = 0; namespace XK { const string ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; void solve() { V C(26), K(26); rep(i, 26) cin >> C[i], C[i] --; rep(i, 26) cin >> K[i]; int N; cin >> N; V S(N); V A(N), B(N), E(N); rep(i, N) cin >> S[i] >> A[i] >> B[i] >> E[i], A[i] --, B[i] --; ll f[30][16][16]{0}, ans[16]{0}; rep(i, 26) { rep(d, 30) rep(j, 16) rep(k, 16) f[d][j][k] = -LINF; rep(d, 30) rep(j, 16) f[d][j][j] = 0; rep(n, N) { if(S[n].find(ALPHA[i]) != string::npos) { int u = A[n], v = B[n]; chmax(f[0][u][v], E[n]); chmax(f[0][v][u], E[n]); } } rep(d, 29) rep(j, 16) rep(k, 16) rep(l, 16) { chmax(f[d + 1][j][l], f[d][j][k] + f[d][k][l]); } ll res[16]{-LINF}; rep(i, 16) res[i] = -LINF; res[C[i]] = 0; rrep(d, 0, 30) if((K[i] >> d) & 1) { ll now[16]; rep(j, 16) now[j] = res[j]; rep(j, 16) rep(k, 16) chmax(now[k], res[j] + f[d][j][k]); rep(j, 16) res[j] = now[j]; } rep(j, 16) { ans[j] += res[j]; chmax(ans[j], -LINF); } } ll aa = -LINF; rep(i, 16) chmax(aa, ans[i]); if(aa > -LINF / 10) cout << aa; else cout << "Impossible"; } }; #else #include "cassert" #include "cmath" #include "cstdint" #include "cstdio" #include "cstdlib" #include "cstring" #include "algorithm" #include "bitset" #include "chrono" #include "complex" #include "deque" #include "functional" #include "iostream" #include "limits" #include "map" #include "numeric" #include "queue" #include "random" #include "set" #include "sstream" #include "string" #include "unordered_map" #include "unordered_set" #include "utility" #include "vector" #include "array" using namespace std; #define int long long using ll = long long; using ull = unsigned long long; const ll INF = 1ll << 60; const ll LINF = 0x1fffffffffffffff; const ll MINF = 0x7fffffffffff; template bool chmax(A& l, const B& r){ return r > l ? l = r, 1 : 0; } template bool chmin(A& l, const B& r){ return r < l ? l = r, 1 : 0; } #define sz(x) ssize(x) #define rep(i, a) for(ll i = 0; i < (a); i ++) #define Rep(i, a, b) for(ll i = (a); i < (b); i ++) #define rrep(i, a, b) for(ll i = (b); i --> (a); ) #define all(x) begin(x), end(x) #define fst first #define snd second #define pb push_back template using V = vector; template using AR = array; #define MAIN #include __FILE__ signed main() {ios::sync_with_stdio(0);cin.tie(0);fixed(cout).precision(12);int t = 1;if(__multi__) cin >> t;while(t --) XK::solve();} #endif