题目传送门
问题描述
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle.
As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
输入
The input consists of an N * N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N^2 integers separated by whitespace (spaces and newlines). These are the N^2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127].
输出
Output the sum of the maximal sub-rectangle.
算法思想
对于一个一维数组, 我们已经知道如何用动态规划的思想求解其最大子段和 (不熟悉的同学可以移步https://blog.csdn.net/MaTF_/article/details/122679311?spm=1001.2014.3001.5501), 其状态转移方程为dp[i]=max(arr[i],dp[i-1]+arr[i])
我们可以尝试将矩阵转化为多个一维数组, 转化方式为: 枚举(i,j)
,满足i<=j
, 将第i
行到第j
行纵坐标相同的元素全部相加(借助差分数组), 构成一个一维数组.
我们对转化而来的每一个一维数组, 分别求其最大字段和, 所有最大子段和中的最大值即为所求答案.
代码实现
#include<iostream>
#include<algorithm>
#define maxn 105
using namespace std;
int n;
int arr[maxn][maxn];
int new_arr[10000][maxn];
int dp[10000][maxn];
int d[maxn][maxn];
int cnt=0;
int _max=-99999999;
void init(){ //将矩阵转化为若干一维数组
for(int i=0;i<n;i++){
for(int j=i+1;j<=n;j++){
for(int k=1;k<=n;k++){
new_arr[cnt][k]=d[j][k]-d[i][k];
}
cnt++;
}
}
}
void find_max(int x){ //求解一维数组的最大子段和
for(int i=1;i<=n;i++){
dp[x][i]=max(new_arr[x][i],dp[x][i-1]+new_arr[x][i]);
}
}
void solve(){ //求解所有一维数组的最大子段和
for(int i=0;i<cnt;i++){
find_max(i);
}
return;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>arr[i][j];
d[i][j]=d[i-1][j]+arr[i][j];
}
}
init();
solve();
for(int i=0;i<cnt;i++){ //遍历找答案
for(int j=1;j<=n;j++){
_max=max(dp[i][j],_max);
}
}
cout<<_max;
return 0;
}