import java.io.File class Dummy val text = File(Dummy::class.java.getResource("input.txt").file).readText() val pattern = """([a-z]+)\((\d+)\)(?:->([a-z,]+))?""".toPattern() val nodes = text.lines().map { val match = pattern.matcher(it.replace(" ", "")).apply { assert(matches()) } val node = Node(match.group(1), match.group(2).toInt(), match.group(3)?.split(",") ?: listOf()) node.name to node }.toMap() data class Node(val name: String, val weight: Int, val children: List) { val totalWeight: Int by lazy { weight + children.sumBy { nodes[it]!!.totalWeight } } } fun main(args: Array) { println( nodes.values.find { (name) -> (nodes.values.none { name in it.children }) }!!.name ) val wrongParent = nodes.values.find { it.children.map { nodes[it]!!.totalWeight }.distinct().size > 1 }!! val children = wrongParent.children.map { nodes[it]!! } val weightCounts = children.map { a -> a.totalWeight to children.count { it.totalWeight == a.totalWeight } }.toMap() val rightChild = children.maxBy { weightCounts[it.totalWeight]!! }!! val wrongChild = children.minBy { weightCounts[it.totalWeight]!! }!! println(wrongChild.weight - (wrongChild.totalWeight - rightChild.totalWeight)) }