Решение
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.util.PriorityQueue
data class CarInfo(
val nextUse: Int,
val id: Int
): Comparable<CarInfo> {
override fun compareTo(other: CarInfo): Int {
return nextUse.compareTo(other.nextUse)
}
}
fun main() {
val reader = BufferedReader(InputStreamReader(System.`in`))
val writer = BufferedWriter(OutputStreamWriter(System.out))
val (N, K, P) = reader.readLine().split(" ").map { it.toInt() }
val requests = IntArray(P)
for (i in 0 until P) {
requests[i] = reader.readLine().toInt()
}
reader.close()
val positions = Array(N + 1) { ArrayDeque<Int>() }
for (i in 0 until P) {
val car = requests[i]
positions[car].addLast(i)
}
for (car in 1..N) {
positions[car].addLast(P + 1)
}
val onFloor = HashSet<Int>(K)
val nextOccur = IntArray(N + 1) { P + 1 }
val pq = PriorityQueue<CarInfo>(compareByDescending<CarInfo> { it.nextUse })
var ops = 0
for (i in 0 until P) {
val car = requests[i]
positions[car].removeFirst()
val nxt = positions[car].firstOrNull() ?: (P + 1)
nextOccur[car] = nxt
if (car in onFloor) {
pq.add(CarInfo(nxt, car))
} else {
ops++
if (onFloor.size < K) {
onFloor.add(car)
pq.add(CarInfo(nxt, car))
} else {
while (true) {
val top = pq.poll() ?: break
val c = top.id
if ((c in onFloor) && top.nextUse == nextOccur[c]) {
onFloor.remove(c)
break
}
}
onFloor.add(car)
pq.add(CarInfo(nxt, car))
}
}
}
writer.write("$ops\\n")
writer.close()
}