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
Problem solving ideas:
The two-dimensionalization of the maximum subsection and the problem
Basic idea: dimensionality reduction processing
Implementation: First select the row where the matrix is located (using a double loop to consider all selection situations)
After selecting the row, it is the problem of selecting which columns Now, take the selected row 2 ~ 4 as an example. That is, i=2 j=4, the maximum value can be obtained by finding the combination of these columns. Since it is always 2 3 4 rows, we can "bundle" these 3 rows to find 4 (9-4-1) ,11(8+2+1),-10(-6-4+0), 7(7+2-2) The maximum sub-segment sum, this problem has been successfully transformed into a one-dimensional case!
After this step, the problem has been successfully transformed into the largest subsection and problem.
Code:
//最大子段和问题的二维化
/*降维*/
#include <cstdio>
#include <cstring>
using namespace std;
int map[110][110];
int temp[110];
int main(){
int n;
int i , j ,max;
while(scanf("%d" ,&n) != EOF){
memset(map , 0 , sizeof(map));
for( i = 1 ; i <= n ; i ++){
for(j = 1 ; j <= n ; j ++){
scanf("%d" , &map[i][j]);
map[i][j] = map[i][j] + map[i-1][j]; //这一步实际上已经实现了一个降维的过程
}
}
max = map[1][1];
for(i = 1 ; i <= n ; i ++){ //i 表示起始行 , j 表示结束行
/*行数确定的情况下,只要确定一下列数就可以 , 这时候就是将 选定行中的同一列中的数字相加
便能够得到一个一维的数组 , 到这步位置就已经将这个问题降维 成 最大子段和 问题了。*/
for(j = i ; j <= n ; j ++){
memset(temp , 0 , sizeof(temp));
for(int k = 1 ; k <= n ; k++) //temp 即为降维之后的一维数组
temp[k] = map[j][k] - map[i-1][k];
for(int k = 1 ; k <= n ; k ++ ){
if(temp[k-1] >= 0)
temp[k] = temp[k -1] + temp[k];
if(temp[k] > max)
max = temp[k];
}
}
}
printf("%d\n",max);
}
return 0;
}