data class Element(val a:Int,val b:Int){ val value = a + b fun canJoin(x: Int) = a==x || b==x fun otherEnd(x:Int) = if (a==x) b else a } typealias Bridge = List fun Bridge.value() = this.sumBy { it.value } tailrec fun buildBridge(x: Int, bridge: Bridge, remaining: List) : Bridge { val links = remaining.filter { it.canJoin(x) } return when (links.size){ 0 -> bridge else -> links.map { buildBridge(it.otherEnd(x), bridge + it, remaining - it) } .maxBy{ it.size * 1000 + it.value() }!! } } fun main(args: Array) { val elements = input.split("\n").map { it.split("/").map(String::toInt)}.map { e-> Element(e[0], e[1])} val strongest = buildBridge(0, listOf(), elements) println(strongest.value()) }