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
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
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
and has a sum of 15.
Input
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
Output the sum of the maximal sub-rectangle.
Sample Input
4
0 -2 -7 0 9 2 -6 2
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0 -2
Sample Output
15
题意:给一个N*N的矩形数组,求其中元素和最大的子矩形,输出最大值。
解析:因为数据比较小,可以枚举每个矩形,但是求矩形和时可以预处理一下。可以设置一个数组比如RecSum[i][j],i,j分别代表行,RecSum[i][j]表示右下角坐标为(i,j)左上角为(1,1)的矩形元素和,那么求某个矩形时,如左上角坐标为(upx,upy),右下角坐标为(lowx,lowy),则体积 V=RecSum[lowx][lowy]-RecSum[upx][lowy]-(RecSum[lowx][upy]-RecSum[upx][upy]);最后找最大值即可。
代码如下:
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<iterator>
#include<utility>
#include<sstream>
#include<iostream>
#include<cmath>
#include<stack>
using namespace std;
const int INF=1000000007;
const double eps=0.00000001;
int N,elem[101][101];
int RowSum[101][101],RecSum[101][101];
inline void Get_RowSum() //处理每一行的前m个数的元素和
{
memset(RowSum,0,sizeof(RowSum));
for(int x=1;x<=N;x++)
for(int y=1;y<=N;y++)
{
if(y==1) RowSum[x][y]=elem[x][y];
else RowSum[x][y]=RowSum[x][y-1]+elem[x][y];
}
}
inline void Get_RecSum() //得到RecSum[][]
{
memset(RecSum,0,sizeof(RecSum));
for(int x=1;x<=N;x++)
for(int y=1;y<=N;y++)
{
if(x==1) RecSum[x][y]=RowSum[x][y];
else RecSum[x][y]=RecSum[x-1][y]+RowSum[x][y];
}
}
inline int Get(int upx,int upy,int lowx,int lowy)
{
return RecSum[lowx][lowy]-RecSum[upx][lowy]-(RecSum[lowx][upy]-RecSum[upx][upy]);
}
int Cal(int row,int col)
{
int ret=-INF;
for(int i=0;i+row<=N;i++) //枚举每个矩形
{
for(int j=0;j+col<=N;j++)
{
int upx=i,upy=j,lowx=i+row,lowy=j+col;
ret=max(ret,Get(upx,upy,lowx,lowy));
}
}
return ret;
}
int main()
{
while(cin>>N)
{
for(int i=1;i<=N;i++)
for(int j=1;j<=N;j++) scanf("%d",&elem[i][j]);
Get_RowSum();
Get_RecSum();
int ans=-INF;
for(int row=1;row<=N;row++) // 枚举矩形大小
for(int col=1;col<=N;col++)
ans=max(ans,Cal(row,col));
cout<<ans<<endl;
}
return 0;
}