Baekjoon algorithm training

[백준] 1966 (프린터 큐)

interfacer_han 2024. 1. 5. 15:43

#1 알고리즘

#1-1 큐

 

[백준] 10845 - 큐

#1 알고리즘 java.util.Stack과는 달리 java.util.Queue는 클래스가 아니라 인터페이스다. 나는 java.util.Queue 인터페이스를 구현한 클래스인 LinkedList를 Queue로서 사용했다. last()는 확장 함수(Extension functions)

kenel.tistory.com

큐(Queue)가 사용되었다는 점에서 비슷한 문제다.

 

#1-2 목표 문서의 인덱스

프린트할 목표 문서의 인덱스를 어떤 변수 A로 두고 추적할 수도 있다. 하지만 이러면 Queue가 offer되거나 poll될 때에 바뀌는 목표 문서의 위치에 맞게 A의 값을 계속 조정해주어야 한다. 이는 가독성에 나쁜 영향을 미치고, 그래서 에러의 여지를 키운다. 나는 코틀린의 Pair 객체를 이용해서, 목표 문서가 목표 문서임을 알 수 있게 표시하여 Queue에 넣었다.

 

#2 코드 - 코틀린

import java.util.LinkedList
import java.util.Queue

fun main() {
    val testCaseCount = readln().toInt()
    for(i: Int in 0..<testCaseCount) {
        // 첫째 줄 읽어들이기
        val printerInformation = readln().split(" ")
        val fileCount = printerInformation[0].toInt()
        val targetFileIndex = printerInformation[1].toInt()

        // 둘째 줄 읽어들이기
        val fileStrings = readln().split(" ")
        val fileQueue: Queue<Pair<Int, String>> = LinkedList()
        for(j: Int in 0..<fileCount) {
            if(j == targetFileIndex) {
                fileQueue.offer(Pair(fileStrings[j].toInt(),"target"))
            } else {
                fileQueue.offer(Pair(fileStrings[j].toInt(),""))
            }
        }

        // 출력
        println(getTargetOrder(fileQueue))
    }
}

fun getTargetOrder(queue: Queue<Pair<Int, String>>): Int {
    var order = 1

    while(true) {
        if(isHighestPriorityOfPeek(queue)) { // peek한 원소가 최고 우선순위면
            if(queue.poll().second == "target") {
                return order
            }
            order++
        } else { // peek한 원소가 최고 우선순위가 아니면
            queue.offer(queue.poll())
        }
    }
}

fun isHighestPriorityOfPeek(queue: Queue<Pair<Int, String>>): Boolean {
    val peekedElement = queue.peek().first

    for(i: Int in 1..<queue.size) {
        if(peekedElement < queue.elementAt(i).first) {
            return false
        }
    }

    return true
}

'Baekjoon algorithm training' 카테고리의 다른 글

[백준] 18110 (solved.ac)  (0) 2024.01.08
[백준] 1874 (스택 수열)  (0) 2024.01.06
[백준] 17626 (Four Squares)  (0) 2024.01.03
[백준] 11399 (ATM)  (0) 2024.01.02
[백준] 1012 (유기농 배추)  (0) 2024.01.01