To the Max
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.
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
Source
这是求二维数组的最大子数组问题,其更为简单的形式是求一维数组的最大连续子段问题。现在还是从一维数组的最大子段问题谈起,对任意一个一维数组a[N](共N个数),用b[j]表示a[N]中包括a[j]的前j个元素的最大连续子段的值。则必有:
b[j] = max{b[j-1]+a[j], a[j]}, 0≤j<N
这样一维数组的最大子段值,就是max{b[j]} 0≤j<N。时间复杂度O(N)。
推广到二维,就是要想办法先将问题变为类似于一维的问题。其具体思想是:对二维数组的包含N行的列进行连续列划分,则共有N*N/2种,分别计算着N*N/2个矩阵的各列的和,则此时二维数组编成了一维数组,然后用一维数组求最大连续子段的方法可以求得需要的结果。时间复杂度O(N^3)。
具体实现如下:
#include "iostream"
using namespace std;
const int N = 100;
int itg[N][N];
int MaxSum(int n, int itmp[])
{
int i, max, tmp;
max = itmp[0];
tmp = itmp[0];
for(i = 1; i < n; i++)
{
// if(itmp > 0) tmp += itmp[i]; //靠,垃圾,害得我WA3次,下次一定好好选择临时变量了。
if(tmp > 0) tmp += itmp[i];
else tmp = itmp[i];
if(max < tmp) max = tmp;
}
return max;
}
int main()
{
int n;
int i, j, k, max;
int itmp[N], tmp;
cin >> n;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
cin >> itg[i][j];
}
}
max = -200;
for(i = 0; i < n; i ++)
{
memset(itmp, 0, sizeof(int)*N);
for(j = i; j < n; j ++)
{
for(k = 0; k < n; k ++) itmp[k] += itg[j][k];
tmp = MaxSum(n, itmp);
if(max < tmp) max = tmp;
}
}
cout << max <<endl;
return 0;
}
执行结果: