상세 컨텐츠

본문 제목

프린터 큐(백준)

코딩테스트

by dofury 2023. 7. 4. 16:09

본문

728x90

 

 

package com.example.algorithm

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


fun main(){
    val testSize = readLine()!!.toInt()

    repeat(testSize){
        val (_, location) = readLine()!!.split(' ').map { it.toInt() }
        val pair = readLine()!!.split(' ').map{it.toInt()}


        val queue: Queue<Pair<Int,Int>> = LinkedList()

        //큐에 추가
        for((index, priority) in pair.withIndex()) {
            queue.add(Pair(priority,index))
        }

        var result = 0

        while(queue.isNotEmpty()){
            val item = queue.poll()//큐 반환

            //현재 우선순위보다 더 높은 pair가 존재하는지 확인
            val higherPriorityExits = queue.any { it.first > item!!.first }

            if(higherPriorityExits) {//우선순위 높은게 존재한다면
                queue.add(item)
            }else{
                result++

                //목표를 찾았을 때 반복 종료
                if(item!!.second == location){
                    break
                }
            }

        }
        println(result)


    }


}

처음에는 우선순위 큐를 이용해서 구현할려고 했었다.

내부적으로 문제가 요구하는 것처럼 한다고 판단했기 때문이다.

하지만 틀렸다고 나와서 큐를 연결리스트로 구현해 문제가 요구하는 것처럼 우선순위 큐를 구현했다.

 

해당 문제를 풀면서 코틀린의 any를 사용하면 리스트 안에 값을 비교해서 결과를 손쉽게 얻을 수 있는 것을 알 수 있었다.

728x90

'코딩테스트' 카테고리의 다른 글

통계학(백준)  (0) 2023.07.06
균형잡힌 세상(백준)  (0) 2023.07.05
수 찾기(백준)  (0) 2023.07.03
체스판 다시 칠하기(백준)  (0) 2023.06.30
ACM 호텔(백준)  (0) 2023.06.29

관련글 더보기

댓글 영역