結果

問題 No.4 おもりと天秤
ユーザー komkomh
提出日時 2019-04-06 21:31:28
言語 Kotlin
(2.1.0)
結果
AC  
実行時間 714 ms / 5,000 ms
コード長 1,207 bytes
コンパイル時間 11,172 ms
コンパイル使用メモリ 434,452 KB
実行使用メモリ 100,044 KB
最終ジャッジ日時 2024-11-20 17:48:38
合計ジャッジ時間 19,577 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 23
権限があれば一括ダウンロードができます

ソースコード

diff #

package yukicoder

fun main() {
    val N: Int = readLine()!!.toInt()
    val W: List<Int> = readLine()!!.split(" ").map(String::toInt)

    val sum: Int = W.sum()
    if (sum % 2 != 0) {
        println("impossible")
        return
    }

    val halfW = sum / 2
    var cache: MutableMap<Pair<Int, Int>, Boolean> = mutableMapOf()
    fun search2(nokori: Int, index: Int): Boolean {
        val currentNokori = nokori - W[index]
        return when {
            currentNokori < 0 -> false
            currentNokori == 0 -> true
            else -> {
                for (i in index + 1 until N) {
                    val key = Pair(currentNokori, i)
                    val result = cache.get(key)?.let {
                        it
                    } ?: run {
                        val result = search2(currentNokori, i)
                        cache.put(key, result)
                        result
                    }
                    if (result) {
                        return result
                    }
                }
                false
            }
        }
    }

    when (search2(halfW, 0)) {
        true -> println("possible")
        false -> println("impossible")
    }
}
0