Description
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.
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.
Input
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
Output the sum of the maximal sub-rectangle.
Sample Input
4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
Sample Output
15
题意:求矩阵中子矩阵的最大矩阵和
解题思路:我们求一维序列中最大子序列用DP从前往后扫一遍即可,那么对于二维的数组我们要想方法转成一维数据来处理,这个是核心的思想,剩下的就是怎么把二维转为一维。我们知道我们只能在一个维度上DP,所以另一个维度就要穷举。
我们选择在X方向上DP而在Y方向上穷举:我们求出每一种Y方向上的DP值,然后取最大值。比如3x3的数据,我们要求出1行DP,1~2行DP,1~3行DP,2行DP,2~3行DP,3行DP,取最大值即可。
下面是2种代码基本思路一致,只是细节上第二种更省时
#include <iostream> using namespace std; #define N 102 int num; int data[N][N];//源数据 int temp[N];//压缩后临时一维数组 int dp() { int max = -(1<<30); int out = temp[0]; for (int i=1; i<num; i++ ) { if (out < 0) out = temp[i]; else out += temp[i]; if (max < out) max = out; } return max; } int main() { cin>>num; int out = -(1<<30); //输入矩形 for (int i=0; i<num; i++) for (int j=0; j<num; j++) cin>>data[i][j]; for (int i=0; i<num; i++) { memset(temp, 0, sizeof(temp));//清空临时一维数组 for (int j=i; j<num; j++) { //求一维数组 for (int k=0; k<num; k++) temp[k] += data[j][k]; //求最大值 int a = dp(); if (out < a) out = a; } } cout<<out<<endl; return 0; }
将DP过程精简在main中,避免了不必要的计算
#include <iostream> using namespace std; #define N 102 int num; int data[N][N];//源数据 int temp[N][N];// int main() { cin>>num; int max = -(1<<30); int out = -(1<<30); //输入矩形 for (int i=1; i<=num; i++) for (int j=1; j<=num; j++) cin>>data[i][j]; for (int i=1; i<=num; i++) for (int j=1; j<=num; j++) temp[i][j] = temp[i][j-1] + data[i][j];//求出temp表 for (int i=1; i<=num; i++) for (int j=i; j<=num; j++) { int a = temp[1][j] - temp[1][i-1]; out = a; for (int k=2; k<=num; k++) { if (out > 0) { out += temp[k][j] - temp[k][i-1]; } else { out = temp[k][j] - temp[k][i-1]; } if (out > a) a = out; } if (a > max) max = a; } cout<<max<<endl; //system("pause"); return 0; }