thangkc89
Senior Member
Bài này e nhìn vô là ra dp ngay mà hoá ra éo phải optimal solutionCơm thêm contest 14 July: https://leetcode.com/problems/minimum-cost-for-cutting-cake-i/description/
nhiều lúc không nghĩ là nó chạy được, cứ nghĩ DP ốm người ko ra
Python:class Solution: def minimumCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int: A, B, res = sorted(horizontalCut), sorted(verticalCut), 0 while A or B: if not A: res += (m - len(A)) * B.pop() elif not B: res += (n - len(B)) * A.pop() elif A[-1] > B[-1]: res += (n - len(B)) * A.pop() else: res += (m - len(A)) * B.pop() return res
vãi Q4, 7 điểm y hệt Q3![]()
Python:
class Solution:
def minimumCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int:
@lru_cache(None)
def dp(x0, y0, x1, y1):
if x1 - x0 == 1 and y1 - y0 == 1:
return 0
res = 10**9
for x in range(x0, x1-1):
res = min(res, dp(x0, y0, x+1, y1) + dp(x+1, y0, x1, y1) + horizontalCut[x])
for y in range(y0, y1-1):
res = min(res, dp(x0, y0, x1, y+1) + dp(x0, y+1, x1, y1) + verticalCut[y])
return res
return dp(0, 0, m, n)

