To the Max
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 36809 | Accepted: 19373 |
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
给定一个矩阵,求和最大的一个子矩阵
容易观察到,最大子矩阵问题是最大连续子序列和问题的提升,即将一条线换成一个面,将一维问题提升到二维问题。所以我们计算最大子矩阵的方法就是将一行行的数进行累加以求得最大值。 但是还有一个问题,那就是应该如何高效地存储矩阵? 我们可以想到:在一个一维的数列中,设数组b[i]表示从第1个元素到第i个元素的和,则如果想要求第i个元素到第j个元素的和,只需要计算b[j]-b[i-1]的值就行了。由此推广到二维矩阵,设b[i,j]表示矩阵第j列前i个元素的和,a[i,j]表示元素数据,则压缩存储: for i:=1 to n do for j:=1 to n do begin read(a[i,j]);b[i,j]:=b[i-1,j]+a[i,j];} 因此,我们可以使用三重循环求出所有的矩形值,即枚举起始行i和终止行j,压缩子矩形成为一行,变成一维求最大子段和问题。 即t[k]=max(t[k-1],0)+b[j,k]-b[i-1,k]; 时间复杂度为O(n3)
代码#include<iostream> using namespace std; int a[101][101],b[101][101]={0},t[101]={0},i,j,k,n,ans=0; int main() { cin>>n; for (i=1;i<=n;i++) for (j=1;j<=n;j++) { cin>>a[i][j]; b[i][j]=b[i-1][j]+a[i][j]; } for (i=1;i<=n;i++) for (j=i;j<=n;j++) { t[1]=b[j][1]-b[i-1][1]; for (k=2;k<=n;k++) { if (t[k-1]>0) t[k]=t[k-1]+b[j][k]-b[i-1][k]; else t[k]=b[j][k]-b[i-1][k]; if (t[k]>ans) ans=t[k]; } } cout<<ans; return 0; }