Kotlin/Algorithm Problems
<백준> 24.05.28에 푼 문제
re트
2024. 5. 28. 17:24
728x90
1. N번째 큰 수 (Silver 2)
[백준]
https://www.acmicpc.net/problem/2075
[깃허브]
ForCodeKata/baekjoon 문제집/N번째 큰 수 at main · heesoo-park/ForCodeKata
알고리즘 문제 코드 저장소. Contribute to heesoo-park/ForCodeKata development by creating an account on GitHub.
github.com
작성한 코드는 다음과 같다.
import java.io.*
import java.util.*
fun main(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
val n = br.readLine().toInt()
val table = Array(n) { ArrayDeque<Int>() }
repeat(n) { it ->
val line = br.readLine().split(' ').map { it.toInt() }
line.forEachIndexed { index, i ->
table[index].add(i)
}
}
var cnt = 0
while (true) {
var maxIndex = 0
cnt++
table.forEachIndexed { index, i ->
if (i.last > table[maxIndex].last) {
maxIndex = index
}
}
if (cnt == n) {
bw.write("${table[maxIndex].last}")
break
}
table[maxIndex].removeLast()
}
bw.flush()
bw.close()
}
(이 문제가 우선순위 큐를 이용하는 걸 원했던 문제라는 것은 내 방식대로 해결하고 다른 사람들의 풀이를 보면서 알게 됐다...)
2. 한 줄로 서기 (Silver 2)
[백준]
https://www.acmicpc.net/problem/1138
[깃허브]
ForCodeKata/baekjoon 문제집/한 줄로 서기 at main · heesoo-park/ForCodeKata
알고리즘 문제 코드 저장소. Contribute to heesoo-park/ForCodeKata development by creating an account on GitHub.
github.com
작성한 코드는 다음과 같다.
import java.io.*
fun main(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
val n = br.readLine().toInt()
val info = br.readLine().split(' ').map { it.toInt() }
val line = IntArray(n)
info.forEachIndexed { idx, num ->
var cnt = 0
var i = 0
while (true) {
if (cnt == num) {
while (line[i] != 0) {
i++
}
line[i] = idx + 1
break
}
if (line[i] == 0) {
while(line[i + 1] != 0) {
i++
}
cnt++
}
i++
}
}
line.forEach {
bw.write("$it ")
}
bw.flush()
bw.close()
}
(그리디 알고리즘이라고 생각이 어렴풋이 들긴 했지만 그냥 접근 자체가 답답했다. 그리고 0이 아닐 때 인덱스를 건너가는 거 구현하는 걸로 한참 시간 썼던 거 같다...)
반응형