Home 백준 - 1021 회전하는 큐
Post
Cancel

백준 - 1021 회전하는 큐

문제

1021 회전하는 큐

screencapture

kotlin code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
fun main() {
    q1021()
}

fun q1021() {
    val queue = CircleQueue()
    queue.addAllElementsOneToN(readln().split(" ").first().toInt())
    val dequeueElements = readln().split(" ").map { it.toInt() }

    var result = 0
    for(element in dequeueElements) {
        result += queue.getNumberOfMinOperationsToGetElement(element)
        queue.getElement(element)
    }
    println(result)
}

class CircleQueue {
    private val queue = mutableListOf<Int>()
    private var curIndex = 0

    fun addAllElementsOneToN(n:Int) {
        queue.addAll(1..n)
    }

    fun getNumberOfMinOperationsToGetElement(element: Int): Int {
        val elementIndex = queue.indexOf(element)
        if(elementIndex == curIndex) return 0
        val largeIndex = kotlin.math.max(elementIndex, curIndex)
        val smallIndex = kotlin.math.min(elementIndex, curIndex)
        return kotlin.math.min(largeIndex-smallIndex, (queue.size + smallIndex) - largeIndex)
    }

    fun getElement(element: Int) {
        val elementIndex = queue.indexOf(element)
        queue.removeAt(elementIndex)
        curIndex = if(queue.isEmpty()) 0 else elementIndex % queue.size
    }
}
This post is licensed under CC BY 4.0 by the author.

백준 - 5430 AC

백준 - 2740 행렬 곱셈