Skip to content

Instantly share code, notes, and snippets.

@dkaraush
Last active December 8, 2025 12:33
Show Gist options
  • Select an option

  • Save dkaraush/75674597d40c379c2aa5b49f2c3c9694 to your computer and use it in GitHub Desktop.

Select an option

Save dkaraush/75674597d40c379c2aa5b49f2c3c9694 to your computer and use it in GitHub Desktop.
import java.io.File
import java.util.SortedSet
fun main() {
val FIRST_SAMPLES_COUNT = 1000
val input = File("input.txt").readLines()
.map { it.split(',').map(String::toLong) }
val circuits = input.withIndex().mapTo(ArrayList())
{ (idx, _) -> hashSetOf(idx) }
fun tryToConnect(a: Int, b: Int): Boolean {
val circuitA = circuits.find { it.contains(a) } ?: return false
val circuitB = circuits.find { it.contains(b) } ?: return false
if (circuitA == circuitB) return false
circuitA.addAll(circuitB)
circuits.remove(circuitB)
return true
}
// for comparison, you don't actually need sqrt() :P
fun distSqr(a: List<Long>, b: List<Long>) =
a.zip(b, Long::minus).sumOf { it * it }
fun closestPairs(): SortedSet<Triple<Int, Int, Long>> {
val pairs = sortedSetOf( compareBy<Triple<Int, Int, Long>> { it.third } )
for (i in 0 until input.size)
for (j in i + 1 until input.size)
pairs.add(Triple(i, j, distSqr(input[i], input[j])))
return pairs
}
val pairs = closestPairs()
for ((i, j) in pairs.take(FIRST_SAMPLES_COUNT)) {
tryToConnect(i, j)
}
val (a, b, c) = circuits.map { it.size }.sorted().takeLast(3)
val result1 = a * b * c
println(result1)
var result2 = 0L
for ((i, j) in pairs.drop(FIRST_SAMPLES_COUNT)) {
if (circuits.size <= 1) break
tryToConnect(i, j)
result2 = input[i][0] * input[j][0]
}
println(result2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment