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


 1 #include<cstdio>
 2 #include<string.h>
 3 using namespace std;
 4 int map[120][120];
 5 int main()
 6 {
 7     int n;
 8     int flag;
 9     int sum;
10     while(scanf("%d",&n)!=EOF)
11     {
12         memset(map,0,sizeof(map));
13         for(int i=1; i<=n; i++)
14             for(int j=1; j<=n; j++)
15             {
16                 scanf("%d",&flag);
17                 map[i][j]+=map[i][j-1]+flag;//先计算每一行的前J列的和
18         for(int i=1; i<=n; i++)
19             for(int j=1; j<=i; j++)//确定子矩阵的左右边界
20             {
21                 int sum=0;
22                 for(int k=1; k<=n; k++)//行数
23                 {
24                     if(sum<0)
25                         sum=0;//如果前几行的和是小于0的,就令sum=0;因为负数越加越小。
26                     sum+=(map[k][i]-map[k][j-1]);//一行一行地加起来,第k行的[i,j]列
27                     if(sum>max)
28                         max=sum;//找出最大值!!!
29                 }
30                             
31             }
32             printf("%d\n",max);
33     }
34     return 0;
35 }

 

posted on 2014-08-05 11:03  Damonll  阅读(155)  评论(0编辑  收藏  举报