#include #include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; template vector> vec2d(int n, int m, T v){ return vector>(n, vector(m, v)); } template vector>> vec3d(int n, int m, int k, T v){ return vector>>(n, vector>(m, vector(k, v))); } template void print_vector(vector v, char delimiter=' '){ if(v.empty()) { cout << endl; return; } for(int i = 0; i+1 < v.size(); i++) cout << v[i] << delimiter; cout << v.back() << endl; } const ll inf = 1e18; ll e(){ return -inf; } ll add(ll x, ll y){ if(x == e()) return e(); if(y == e()) return e(); return x+y; } ll op(ll x, ll y){ if(x == e()) return y; if(y == e()) return x; return max(x, y); } using Mat = vector>; Mat prod(Mat m1, Mat m2){ int n = m1.size(); Mat ans = vec2d(n, n, e()); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ for(int k = 0; k < n; k++){ ans[i][j] = op(ans[i][j], add(m1[i][k], m2[k][j])); } } } return ans; } Mat pow_mat(Mat a, ll k) { assert(k >= 0); int n = a.size(); Mat ans = vec2d(n, n, e()); for(int i = 0; i < n; i++) ans[i][i] = 0; while (k > 0) { if (k&1) ans = prod(ans, a); a = prod(a, a); k >>= 1; } return ans; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; vector c(26), k(26); for(int i = 0; i < 26; i++) { cin >> c[i]; c[i]--; } for(int i = 0; i < 26; i++) cin >> k[i]; vector A = vec3d(26, 16, 16, e()); int n; cin >> n; for(int i = 0; i < n; i++){ string s; int a, b, e; cin >> s >> a >> b >> e; a--; b--; for(char c: s){ int idx = c-'A'; A[idx][a][b] = op(e, A[idx][a][b]); A[idx][b][a] = op(e, A[idx][b][a]); } } vector B = vec3d(26, 16, 16, e()); for(int i = 0; i < 26; i++){ for(int j = 0; j < 16; j++) A[i][j][j] = 0; B[i] = pow_mat(A[i], k[i]); } ll ans = -inf; for(int i = 0; i < 16; i++){ ll tmp = 0; bool ok = true; for(int j = 0; j < 26; j++){ if(B[j][c[j]][i] == e()) { ok = false; break; } tmp += B[j][c[j]][i]; } if(ok) chmax(ans, tmp); } if(ans == -inf) { cout << "Impossible" << endl; }else{ cout << ans << endl; } }