use std::cmp::*; // https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 macro_rules! input { ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; } macro_rules! input_inner { ($next:expr) => {}; ($next:expr,) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; } macro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ($(read_value!($next, $t)),*) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, usize1) => (read_value!($next, usize) - 1); ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error")); } const INF: i64 = 1 << 55; fn squmul(a: &[Vec], b: &[Vec]) -> Vec> { let n = a.len(); let mut ret = vec![vec![-INF; n]; n]; for i in 0..n { for j in 0..n { for k in 0..n { ret[i][k] = max(ret[i][k], a[i][j] + b[j][k]); } } } ret } fn squpow(a: &[Vec], mut e: i64) -> Vec> { let n = a.len(); let mut sum = vec![vec![-INF; n]; n]; for i in 0..n { sum[i][i] = 0; } let mut cur = a.to_vec(); while e > 0 { if e % 2 == 1 { sum = squmul(&sum, &cur); } cur = squmul(&cur, &cur); e /= 2; } sum } fn main() { input! { c: [usize1; 26], k: [i64; 26], n: usize, sabe: [(chars, usize1, usize1, i64); n], } let mut g = vec![vec![vec![-INF; 32]; 32]; 26]; for (s, a, b, e) in sabe { for &c in &s { let idx = (c as u8 - b'A') as usize; g[idx][a][b] = max(g[idx][a][b], e); g[idx][b][a] = max(g[idx][b][a], e); } } let mut ans = vec![vec![]; 26]; for i in 0..26 { for j in 0..16 { g[i][j + 16][j] = 0; g[i][j + 16][j + 16] = 0; } let pw = squpow(&g[i], k[i] + 1); ans[i] = pw[c[i] + 16].clone(); } let mut ma = -INF; for i in 0..16 { let mut tot = 0; for j in 0..26 { tot += ans[j][i]; } ma = max(ma, tot); } if ma > -INF / 2 { println!("{}", ma); } else { println!("Impossible"); } }