Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sprint5.fin.A
- import java.io.BufferedReader
- import java.io.InputStreamReader
- import java.util.*
- data class Student(val name: String, val passedCount: Int, val penalty: Int) : Comparable<Student> {
- override fun compareTo(other: Student): Int =
- compareBy<Student> { it.passedCount }
- .thenByDescending { it.penalty }
- .thenByDescending { it.name }
- .compare(this, other)
- }
- fun main() {
- val buffer = BufferedReader(InputStreamReader(System.`in`))
- List(buffer.readLine().toInt()) {
- val tokenizer = StringTokenizer(buffer.readLine())
- Student(tokenizer.nextToken(), tokenizer.nextToken().toInt(), tokenizer.nextToken().toInt())
- }
- .heapSort()
- .joinToString("\n") { it.name }
- .let(::println)
- }
- fun <T : Comparable<T>> List<T>.heapSort(): List<T> {
- return MyHeap<T>()
- .also { heap ->
- this.forEach { heap.put(it) }
- }
- .let { heap ->
- buildList {
- while (!heap.isEmpty)
- add(heap.pop())
- }
- }
- }
- class MyHeap<T : Comparable<T>> {
- private val heap: MutableList<T?> = mutableListOf(null)
- val isEmpty
- get() = heap.size == 1
- fun put(element: T) {
- heap.add(element)
- siftUp(heap.lastIndex)
- }
- fun pop(): T {
- heap.swap(1, heap.lastIndex)
- return heap.removeLast()
- .also { siftDown(1) }!!
- }
- private fun siftDown(idx: Int): Int {
- val left = (idx * 2).takeIf { it < heap.size }
- val right = left?.let { it + 1 }?.takeIf { it < heap.size }
- val children = listOfNotNull(left, right)
- return if (children.isEmpty()) idx
- else children
- .filter { heap[it]!! > heap[idx]!! }
- .maxByOrNull { heap[it]!! }
- ?.let {
- heap.swap(it, idx)
- siftDown(it)
- }
- ?: idx
- }
- private fun siftUp(idx: Int): Int {
- if (idx == 1) return idx
- val parent = idx / 2
- if (heap[parent]!! > heap[idx]!!) return idx
- heap.swap(parent, idx)
- return siftUp(parent)
- }
- private fun MutableList<T?>.swap(left: Int, right: Int) {
- val tmp = this[left]
- this[left] = this[right]
- this[right] = tmp
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement