• Home
  • About
    • Moon photo

      Moon

      개발자는 자고 싶다.

    • Learn More
    • Twitter
    • Facebook
    • Instagram
    • Github
    • Steam
  • Posts
    • All Posts
    • All Tags
  • Projects

백준 - 1021 회전하는 큐

06 Jun 2022

Reading time ~1 minute

문제

1021 회전하는 큐

screencapture

답

kotlin code

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
    }
}


baekjoonkotlin코틀린백준실버자료 구조덱 Share Tweet +1