KotlinAlgorithm#11 (BOJ2346)


BOJ 2346風船を破る


リンク

コード#コード#

import java.io.*
import java.util.*
import kotlin.collections.ArrayList

fun main() {
    val br = BufferedReader(InputStreamReader(System.`in`))
    val bw = BufferedWriter(OutputStreamWriter(System.out))

    val N = br.readLine().toInt()
    val input = StringTokenizer(br.readLine())
    val balloon: ArrayList<Pair<Int, Int>> = ArrayList()

    repeat(N) {balloon.add(Pair(it+1, input.nextToken().toInt()))}

    var idx = 0
    while(balloon.isNotEmpty()) {
        var move = balloon[idx].second
        val size = balloon.size - 1
        bw.write("${balloon[idx].first} ")
        balloon.removeAt(idx)

        if(move > 0)    move--
        idx = try { (idx + move) % size }
            catch (e: ArithmeticException) { 0 }
        if(idx < 0) idx += size
    }

    bw.flush()
    bw.close()
    br.close()
}

Deque(メモリオーバーフロー)


テックを通過しますが、LinkedListと宣言するとメモリが爆発します.
import java.io.*
import java.util.*
import kotlin.collections.ArrayDeque
import kotlin.math.abs

fun main() {
    val br = BufferedReader(InputStreamReader(System.`in`))
    val bw = BufferedWriter(OutputStreamWriter(System.out))

    val N = br.readLine().toInt()

    val input = StringTokenizer(br.readLine())

    val balloon: Deque<Pair<Int, Int>> = LinkedList()
    for(i in 0 until N) { balloon.addLast(Pair(i+1, input.nextToken().toInt())) }

    var tmp = balloon.pollFirst()
    bw.write("${tmp.first} ")

    repeat(N-1) {
        when{
            tmp.second > 0 -> {
                repeat(tmp.second) {
                    balloon.offerLast(balloon.pollFirst())
                }
                tmp = balloon.pollLast()
                bw.write("${tmp.first} ")
            }
            tmp.second < 0 -> {
                repeat(abs(tmp.second)) {
                    balloon.offerFirst(balloon.pollLast())
                }
                tmp = balloon.pollFirst()
                bw.write("${tmp.first} ")
            }
        }
    }

    bw.flush()
    bw.close()
    br.close()
}