lc1547 切割棍子的最小成本

有一根长度为n的木棍,从0到n标记了若干个位置。给定一个数组cuts[m],表示要在cuts[i]位置切开,每次切割的成本是当前木棍的长度,求总成本的最小值。
2<=n<=1e6; 1<=m<=min(n-1,100); 1<=cuts[i]<=n-1; cuts[i]各不相同

正向思考的话可以记忆化dfs,也可以逆向思考,转成合并问题,用区间dp求解。这里用的是记忆化dfs。

class Solution {
public:
    int dp[105][105];
    int minCost(int n, vector<int>& cuts) {
        int m = cuts.size();
        sort(cuts.begin(), cuts.end());
        memset(dp, -1, sizeof(dp));
        auto sum = [&](int L, int R) -> int {
            int x = 0, y = n;
            if (L != 0) x = cuts[L-1];
            if (R != m-1) y = cuts[R+1];
            return y-x;
        };
        auto dfs = [&](auto self, int L, int R) -> int {
            if (L > R) return 0;
            if (dp[L][R] != -1) return dp[L][R];
            int ans = 1e9;
            for (int i = L; i <= R; i++) {
                ans = min(ans, self(self,L,i-1) + self(self,i+1,R));
            }
            ans += sum(L,R);
            return dp[L][R] = ans;
        };
        return dfs(dfs, 0, m-1);
    }
};
posted @ 2024-03-21 22:09  chenfy27  阅读(2)  评论(0编辑  收藏  举报