From 977a9058194ec560b32bc9d841e1712b42f4e76e Mon Sep 17 00:00:00 2001 From: isaiahliu Date: Wed, 25 Dec 2024 14:06:29 +0800 Subject: [PATCH] 1 --- src/main/kotlin/p32xx/Problem3218.kt | 51 ++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/kotlin/p32xx/Problem3218.kt diff --git a/src/main/kotlin/p32xx/Problem3218.kt b/src/main/kotlin/p32xx/Problem3218.kt new file mode 100644 index 00000000..2e867b08 --- /dev/null +++ b/src/main/kotlin/p32xx/Problem3218.kt @@ -0,0 +1,51 @@ +package p32xx + +import util.expect + +fun main() { + class Solution { + fun minimumCost(m: Int, n: Int, horizontalCut: IntArray, verticalCut: IntArray): Int { + val cache = hashMapOf, Pair>, Int>() + + fun dfs(hStart: Int, hEnd: Int, vStart: Int, vEnd: Int): Int { + val cacheKey = (hStart to hEnd) to (vStart to vEnd) + + return when { + hStart > hEnd && vStart > vEnd -> 0 + cacheKey in cache -> cache[cacheKey] ?: 0 + else -> { + var min = Int.MAX_VALUE + + (hStart..hEnd).forEach { + min = minOf(min, horizontalCut[it] + dfs(hStart, it - 1, vStart, vEnd) + dfs(it + 1, hEnd, vStart, vEnd)) + } + (vStart..vEnd).forEach { + min = minOf(min, verticalCut[it] + dfs(hStart, hEnd, vStart, it - 1) + dfs(hStart, hEnd, it + 1, vEnd)) + } + + cache[cacheKey] = min + min + } + } + } + + return dfs(0, horizontalCut.lastIndex, 0, verticalCut.lastIndex) + } + } + + expect { + Solution().minimumCost( + 4, 5, + intArrayOf(0, 3), + intArrayOf(0, 2), + ) + } +// expect { +// Solution().shortestDistanceAfterQueries( +// 100000, +// Array(100000 - 1) { +// intArrayOf(0, it + 1) +// } +// ) +// } +}