题目描述
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1 x 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.
输入
The input consists of an N x 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 the sum of the maximal sub-rectangle.
示例输入
4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
示例输出
15
1 #include<stdio.h> 2 #include<string.h> 3 int dp(int a[],int n) 4 { 5 int i,f[200]; 6 int max=-200000000; 7 f[1]=a[1]; 8 for(i=2; i<=n; i++) 9 { 10 if(f[i-1]>0) 11 f[i]=f[i-1]+a[i]; 12 else f[i]=a[i]; 13 if(max<f[i]) 14 max=f[i]; 15 } 16 return max; 17 } 18 19 int main() 20 { 21 int i,n,sum1,j; 22 int a[200][200],k; 23 int sum[200],max; 24 while(~scanf("%d",&n)) 25 { 26 for(i=1; i<=n; i++) 27 for(j=1; j<=n; j++) 28 scanf("%d",&a[i][j]); 29 max=-200000000; 30 for(i=1; i<=n; i++) 31 { 32 memset(sum,0,sizeof(sum)); 33 for(j=i; j<=n; j++) 34 { 35 for(k=1; k<=n; k++) 36 sum[k]+=a[j][k]; 37 sum1=dp(sum,n); 38 if(sum1<0)sum1=0; 39 if(sum1>max)max=sum1; 40 } 41 } 42 printf("%d ",max); 43 } 44 45 return 0; 46 }
1 #include<stdio.h> 2 #include<string.h> 3 #define MAXN 105 4 int main() 5 { 6 int i,j,k,n,t,sum,max; 7 int a[MAXN][MAXN]; 8 while (scanf("%d",&n)!=EOF) 9 { 10 memset(a,0,sizeof(a)); 11 for (i=1; i<=n; ++i) 12 { 13 for (j=1; j<=n; ++j) 14 { 15 scanf("%d",&t); 16 a[i][j]=a[i-1][j]+t; 17 } 18 } 19 max=0; 20 for (i=1; i<=n; ++i) 21 { 22 for (j=i; j<=n; ++j) 23 { 24 sum=0; 25 for (k=1; k<=n; ++k) 26 { 27 t=a[j][k]-a[i-1][k]; 28 sum+=t; 29 if (sum<0) sum=0; 30 if (sum>max) max=sum; 31 } 32 } 33 } 34 printf("%d ",max); 35 } 36 return 0; 37 }