4 切割纸片

4 切割纸片

作者: 赵晓鹏时间限制: 1S章节: 动态规划与贪心

---------------------------------输入

6 4
1 1 0 1
0 0 0 1
0 0 0 1
0 0 0 1
0 0 1 1
0 0 1 1

--------------------输出结果

4
 

#include <iostream>
#include <vector>
#include <climits>

using namespace std;

int minCut(vector<vector<int>>& paper, int startRow, int endRow, int startCol, int endCol, vector<vector<vector<vector<int>>>>& dp) {
    // 如果已经计算过该区域的最小切割数,直接返回结果
    if (dp[startRow][endRow][startCol][endCol] != -1) {
        return dp[startRow][endRow][startCol][endCol];
    }

    // 检查当前区域是否是全带洞的纸片或完整的纸片
    bool allHoles = true;
    bool allIntact = true;
    for (int i = startRow; i < endRow; i++) {
        for (int j = startCol; j < endCol; j++) {
            if (paper[i][j] == 1) {
                allIntact = false;
            }
            else {
                allHoles = false;
            }
            if (!allHoles && !allIntact) {
                break;
            }
        }
        if (!allHoles && !allIntact) {
            break;
        }
    }

    // 如果是全带洞的纸片或完整的纸片,则返回0
    if (allHoles || allIntact) {
        dp[startRow][endRow][startCol][endCol] = 0;
        return 0;
    }

    int minCuts = INT_MAX;

    // 水平切割
    for (int i = startRow + 1; i < endRow; i++) {
        int cuts = minCut(paper, startRow, i, startCol, endCol, dp) + minCut(paper, i, endRow, startCol, endCol, dp) + 1;
        minCuts = min(minCuts, cuts);
    }

    // 垂直切割
    for (int j = startCol + 1; j < endCol; j++) {
        int cuts = minCut(paper, startRow, endRow, startCol, j, dp) + minCut(paper, startRow, endRow, j, endCol, dp) + 1;
        minCuts = min(minCuts, cuts);
    }

    dp[startRow][endRow][startCol][endCol] = minCuts;
    return minCuts;
}

int main() {
    int m, n;
    cin >> m >> n;

    vector<vector<int>> paper(m, vector<int>(n));
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> paper[i][j];
        }
    }

    // 初始化dp数组为-1
    vector<vector<vector<vector<int>>>> dp(m, vector<vector<vector<int>>>(m + 1, vector<vector<int>>(n, vector<int>(n + 1, -1))));

    int minCuts = minCut(paper, 0, m, 0, n, dp);
    cout << minCuts << endl;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨骅麟(Patrick Young)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值