To The Max
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9268 Accepted Submission(s): 4495
Problem Description
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.
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 -4 1 -4 1 -1 8 0 -2
Sample Output
15
这个是动态规划的最大子矩阵,跟最大子段的区别就是它是二维
的!所以要把它压缩成一维!这里的意思就是先算出每一列,再
算出每一行
这一题就是将一维的最大字段和扩展到二维,在一维的求最大字段和的过程中是这样操作的:
int max_sum(int n)
{
int i, j, sum = 0, max = -10000;
for(i = 1; i <= n; i++)
{
if(sum < 0)
sum = 0;
sum += a[i];
if(sum > max)
max = sum;
}
return sum;
}
扩展到二维的时候也是同样的方法,不过需要将二维压缩成一维,所以我们要将数据做一下处理,使得map[i][j]从表示第i行第j个元素变成表示第i行前j个元素和,这样map[k][j]-map[k][i]就可以表示第k行从i->j列的元素和。只要比一维多两层循环枚举i和j就行了。
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int map[105][105];
int maxs;
int main()
{
int n,i,j,v,k,sum;
while(cin>>n)
{
memset(map,0,sizeof(map));
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>v;
map[i][j]=map[i][j-1]+v;
}
}//这个的每一列的每一个数字是前面的数字之和!这样就确保了每一列是线性的!
maxs=-100000;
for(i=1;i<=n;i++)
{
for(j=i;j<=n;j++)
{
sum=0;
for(k=1;k<=n;k++)
{
sum+=map[k][j]-map[k][i-1];//每一行再进行线性就可以实现二维数组的动态规划!
if(sum<0)
{
sum=0;
}
if(sum>maxs)
{
maxs=sum;
}
}
}
}
cout<<maxs<<endl;
}
}