import scala.io.StdIn.readLine import scala.reflect.ClassTag import scala.math.* type Matrix = Array[Array[Option[Long]]] extension (left: Matrix) inline def *(right: Matrix): Matrix = val row = left.length val column = right(0).length val mid = right.length Array.tabulate(row){i => Array.tabulate(column){j => (0 until mid).foldLeft(None: Option[Long]){(acc, k) => (acc, left(i)(k).flatMap(l => right(k)(j).map(r => l + r))) match case (Some(a), Some(b)) => Some(max(a, b)) case (None, r) => r case (l, None) => l } } } inline def pow(exp: Int): Matrix = val size = left.length var result = Array.tabulate(size){i => Array.tabulate(size){j => if i == j then Some(0L) else None}} var base = left var e = exp while e > 0 do if (e & 1) == 1 then result *= base base *= base e >>= 1 result @main def main = val initialColor = readLine().split(' ').map(_.toInt - 1) val maxCount = readLine().split(' ').map(_.toInt) val n = readLine().toInt val skill = Array.fill(n){ val Array(s, a, b, e) = readLine().split(' ') (s, a.toInt - 1, b.toInt - 1, e.toLong) } val graph = Array.fill(26){Array.tabulate(16){i => Array.tabulate(16){j => if i == j then Some(0L) else None}}} for (s, a, b, e) <- skill do for i <- s.map(_ - 'A') do graph(i)(a)(b) = Some(max(graph(i)(a)(b).getOrElse(e), e)) graph(i)(b)(a) = Some(max(graph(i)(b)(a).getOrElse(e), e)) for i <- 0 until 26 do graph(i) = graph(i).pow(maxCount(i)) var result = Long.MinValue for dest <- 0 until 16 do (0 until 26).foldLeft(Some(0L): Option[Long]){(acc, i) => acc.flatMap{a => graph(i)(initialColor(i))(dest).map(a + _)}} match case Some(sum) => result = max(result, sum) case None => println(if result == Long.MinValue then "Impossible" else result)