L1-7 To the Max

本文介绍如何利用动态规划解决给定二维数组中最大子矩形和问题,讲解了两种不同的起始位置(matrix[0][0]和matrix[1][1]),并提供了详细的代码实现。通过遍历每个位置作为子矩形的左上角,计算其与周围矩形的和,找到最大和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给出一个由正整数和负整数组成的二维数组,一个子矩形是指位于整 个数组中大小为1*1或更大的任何连续子数组。矩形的和是该矩形中所 有元素的和。在本题中,具有最大和的子矩形被称为最大子矩形。 例如,给出一个二维数组如下:

\begin{matrix} 0 & -2 & -7 & 0\\ 9 & 2 & -6 & 2\\ -4 & 1 & -4 & 1\\ -1 & 8 & 0 & -2 \end{matrix}

最大子矩形是在左下角:

\begin{matrix} 9 & 2\\ -4 & 1\\ -1 & 8 \end{matrix}

矩形的和是15。

输入格式:

输入给出一个N*N个整数组成的数组。输入的第一行给出一个正整数N,表示二维正方形数组的大小。后面给出用空白字符(空格和换行符)分隔的N2个整数。这些整数是数组的N2 个整数,以行为顺序按行给出。也就是说,首先,第一行从左到右,给出第一行的所有数字;然后,再第二行从左到右,给出第二行的所有数字,以此类推,N的最大值可以是100。数组中的数字的范围是[-127, 127]。

输出格式:

输出最大子矩形的和。

输入样例:

在这里给出一组输入。例如:

4
0 -2 -7 0 
9 2 -6 2 
-4 1 -4 1 
-1 8 0 -2

输出样例:

在这里给出相应的输出。例如:

15

 思路:

看题意不难想到使用动态规划来解,本题思路与LeetCode-304. 二维区域和检索 - 矩阵不可变题解大同小异,可以看一下力扣对此题的官方图解

简单来说就是维护一个数组dp,dp[i][j]表示在matrix[i][j]左上方的矩形区域内所有元素的和。

Q: 但是子矩形不一定是从matrix[0][0]开始啊?

A: 只需要遍历每一个位置,定为子矩形的左上角,再遍历左上角的所有右下区域的每一个坐标,根据sum = dp[i-1][j-1] - dp[p][j-1] - dp[i-1][q] + dp[p][q];就能算出每一个子矩形(左上角为[i, j],右下角为[p, q])的和了

参考代码:

#include<bits/stdc++.h>
using namespace std;

const int MAXSIZE = 100+10;
int dp[MAXSIZE][MAXSIZE];
int matrix[MAXSIZE][MAXSIZE];

int main() {
    int n;  cin>>n;
    for(int i=1;i<=n;++i) {
        for(int j=1;j<=n;++j) {
            cin>>matrix[i][j];
            dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + matrix[i][j];
        }
    }
    int res = -128;
    for(int i=1;i<=n;++i) {
        for(int j=1;j<=n;++j) {
            for(int p=i;p<=n;++p) {
                for(int q=j;q<=n;++q) {
                    res = max(res, dp[i-1][j-1] - dp[p][j-1] - dp[i-1][q] + dp[p][q]);
                }
            }
            
        }
    }
    cout<<res<<endl;
    return 0;
}

上面的代码由于从matrix[1][1]开始记录数据,所以不需要考虑边界情况,但意思可能不够直观的,也可以从matrix[0][0]开始记录数值:

#include<bits/stdc++.h>
using namespace std;

const int MAXSIZE = 100+10;
int dp[MAXSIZE][MAXSIZE];
int matrix[MAXSIZE][MAXSIZE];

int main() {
    int n;  cin>>n;
    for(int i=0;i<n;++i) {
        for(int j=0;j<n;++j) {
            cin>>matrix[i][j];
        }
    }
    dp[0][0] = matrix[0][0];
    for(int i=1;i<n;++i) {
        dp[0][i] = dp[0][i-1] + matrix[0][i];
        dp[i][0] = dp[i-1][0] + matrix[i][0];
    }
    for(int i=1;i<n;++i) {
        for(int j=1;j<n;++j) {
            dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + matrix[i][j];
        }
    }
    int res = -128;
    int curSum = 0;
    for(int i=0;i<n;++i) {
        for(int j=0;j<n;++j) {
            for(int p=i;p<n;++p) {
                for(int q=j;q<n;++q) {
                    curSum = 0;
                    if(j > 0) curSum += -dp[p][j-1];
                    if(i > 0) curSum += -dp[i-1][q];
                    if(i > 0 && j > 0) curSum += dp[i-1][j-1];
                    res = max(res, curSum + dp[p][q]);
                }
            }
            
        }
    }
    cout<<res<<endl;
    return 0;
}

 

 

uz-UZ-Latn api-ms-win-core-localization-l1-2-1 Failed to resolve full path to executable %ls. sr-BA-Latn div-MV LOADER: length of teporary directory path exceeds maximum path length! Wednesday advapi32 sma-se ext-ms-win-ntuser-windowstation-l1-1-0 Friday Tuesday zh-cht api-ms-win-core-fibers-l1-1-1 HH:mm:ss Failed to get address for %hs PyInstaller Onefile Hidden Window MM/dd/yy smj-no D:(A;;FA;;;%s)(A;;FA;;;%s) WARNING CreateDirectory uz-uz-cyrl Failed to load Python DLL '%ls'. api-ms-win-core-fibers-l1-1-2 api-ms-win-core-sysinfo-l1-2-1 quz-ec GetModuleFileNameW zh-CHS Failed to execute script '%ls' due to unhandled exception: %ls kok-IN Needs to remove its temporary files. sr-BA-Cyrl api-ms-win-rtcore-ntuser-window-l1-1-0 LOADER: failed to create runtime-tmpdir path %ls! mscoree.dll Failed to convert executable path to UTF-8. sr-sp-cyrl S-1-3-4 az-AZ-Cyrl #+3;CScs az-AZ-Latn sma-NO LOADER: failed to obtain the absolute path of the runtime-tmpdir. January GetProcAddress quz-EC February api-ms-win-core-file-l2-1-4 api-ms-win-core-localization-obsolete-l1-2-0 sms-fi smn-FI az-az-latn smn-fi October Security descriptor string length exceeds PYI_PATH_MAX! div-mv api-ms-win-security-systemfunctions-l1-1-0 sr-SP-Cyrl ext-ms- smj-se bs-ba-latn api-ms-win-core-file-l1-2-2 Unhandled exception in script quz-pe VCRUNTIME140.dll Saturday ext-ms-win-ntuser-dialogbox-l1-1-0 LOADER: failed to expand environment variables in the runtime-tmpdir. [PYI-%d:ERROR] api-ms-win-core-synch-l1-2-0 kok-in LOADER: failed to set the TMP environment variable. api-ms-win-core-processthreads-l1-1-2 api-ms-win-core-xstate-l2-1-0 Failed to obtain/convert traceback! LoadLibrary sr-SP-Latn smj-NO Failed to obtain executable path. ((((( H api-ms-win-core-file-l1-2-4 sma-no quz-BO STATIC <FormatMessageW failed.> api-ms-win-core-string-l1-1-0 [PYI-%d:%ls] sma-SE quz-PE user32 VCRUNTIME140_1.dll Failed to create child process! api-ms-win-appmodel-runtime-l1-1-2 November api-ms-win-core-datetime-l1-1-1 api-ms-win-core-winrt-l1-1-0 CreateProcessW August zh-CHT kernelbase PyInstallerOnefileHiddenWindow Thursday D:(A;;FA;;;%s) (null) CONOUT$ LOADER: failed to convert runtime-tmpdir to a wide string. az-az-cyrl December September Monday LOADER: runtime-tmpdir points to non-existent drive %ls (type: %d)! smj-SE uz-uz-latn BUTTON ]Warning UTF-16LEUNICODE kernel32 sr-ba-latn syr-sy Sunday sr-sp-latn uz-UZ-Cyrl api-ms- bs-BA-Latn dddd, MMMM dd, yyyy zh-chs sr-ba-cyrl sms-FI syr-SY _MEI%d ( quz-bo / P6pL /-P?pR ,/KPip 判断是否是木马字符。
最新发布
05-26
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

「江太白」

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

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

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

打赏作者

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

抵扣说明:

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

余额充值