To the Max
Time Limit: 1000MS | | Memory Limit: 10000K |
|
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
解题思路:穷举和打表法,即存储一些中间值,避免重复的计算
#include<stdio.h> int main(){ int **p;//存储输入矩阵 int **r;//存储子矩阵的和 int n;//n*n矩阵 int x=0,y=0,z,h;//(x,y)(z,h)确定一个子矩阵,其中(x,y)为左上坐标,(z,h)为右下坐标。 int max;//output scanf("%d",&n); //分配内存空间 p=new int*[n]; r=new int*[n]; for(int i=0;i<n;i++){ p[i]=new int[n]; r[i]=new int[n]; for(int j=0;j<n;j++){ scanf("%d",&p[i][j]); } } //给一个初始值 max=p[0][0]; int rowcount=0;// for(x=0;x<n;x++){ for(y=0;y<n;y++){ r[x][y]=p[x][y];//开始打表,(x,y)确定了子矩阵的左上坐标。 for(z=x;z<n;z++){ rowcount=0;//对第z行元素进行累加,可以避免重复计算。 for(h=y;h<n;h++){ rowcount +=p[z][h]; if(z>x) r[z][h]=rowcount+r[z-1][h]; else r[z][h]=rowcount; if(r[z][h]>max) max=r[z][h]; } } } } printf("%d",max); return 0; }