백준 31792번 한빛미디어 (Hard) Kotlin

: ) YOUNG·2025년 7월 11일
1

알고리즘

목록 보기
479/483

백준 31792번 한빛미디어 (Hard) Kotlin

https://www.acmicpc.net/problem/31792

문제



생각하기




동작



결과


코드



import java.io.BufferedWriter
import java.io.File
import java.io.OutputStreamWriter
import java.util.*

// input
private var br = System.`in`.bufferedReader()

// variables
private var N = 0

fun main() {
    val bw = BufferedWriter(OutputStreamWriter(System.out))

    input()
    bw.write(solve())
    bw.close()
} // End of main()

private fun solve(): String {
    val sb = StringBuilder()

    val treeMap = TreeMap<Int, Int>()
    repeat(N) {
        val line = br.readLine()
        val st = StringTokenizer(line)
        val cmd = st.nextToken().toInt()

        if (cmd == 1) {
            val S = st.nextToken().toInt()
            treeMap[S] = treeMap.getOrDefault(S, 0) + 1
        } else if (cmd == 2) {
            val S = st.nextToken().toInt()
            if (treeMap.containsKey(S)) {
                treeMap[S] = treeMap[S]!! - 1
                if (treeMap[S] == 0) treeMap.remove(S)
            }
        } else {
            var pageCount = 0
            if (treeMap.isNotEmpty()) {
                pageCount = 1
                var curS: Int? = treeMap.firstKey() // 1. var로 선언하고, null 가능 타입으로 변경

                while (true) {
                    // 현재 페이지(curS)를 기준으로 다음 페이지의 시작점을 찾음
                    val nextS = treeMap.higherKey(curS!! * 2 - 1)

                    if (nextS != null) {
                        // 다음 페이지가 존재하면,
                        pageCount++      // 페이지 수 증가
                        curS = nextS     // 기준점을 다음 페이지로 갱신
                    } else {
                        // 다음 페이지가 없으면 반복 종료
                        break
                    }
                }
            }

            sb.append(pageCount).append('\n')
        }
    }

    return sb.toString()
} // End of solve()

private fun input() {
    N = br.readLine().toInt()
} // End of input()

0개의 댓글