/** * Idea is to calculate the distance per color from the previous stitch and decide based on the distance to go though * the back or stop and start at the next stitch. * The timelimit seems way to high or im way of that I missed an important usecase where this won't work. */ fun main() { val input = System.`in`.bufferedReader() val (back, use, start) = input.readLine().split(" ").take(3).map { it.toLong() } val colors = input.readLine().toList() val pattern = input.readLine().toList() val startAndEnd = 2 * start fun List.calculateCost(): Long { if (isEmpty()) return 0L return windowed(2) .fold(startAndEnd + use) { acc, (left, right) -> acc + use + when (val diff = right - left) { 1 -> 0 else -> when (val backPrice = (diff - 1) * back) { in 0..startAndEnd -> backPrice // it is cheaper to go through the back else -> startAndEnd // it is cheaper to stop and start the color later } } } } val distance = pattern.asSequence().withIndex().groupBy { it.value } .mapValues { list -> list.value.map { it.index }.calculateCost() } colors.forEach { println(distance[it] ?: 0) } // corner case when a color is not used in the pattern }