To The Max
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9109 Accepted Submission(s): 4421
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.
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
Source
这个题 我也是醉了,首先说明一点,这题目 看人家解题报告提示了。试想如果某个子矩阵和最大 ,那么把他们所在的行压缩为一行,则必然此连续子序列和最大。问题转化
技巧所在,并且可以这样划分,检查所有压缩组合,从第一行开始,检查所有包含此行的往下的行的子矩阵,找出包含此行的子矩阵最大值,接着检查包涵下一行的往下的所有
子矩阵。检查所有后,必然产生一个最大值咯。
最他妈气人的是,前几次wa 之后什么都没有该 一会就ac了 ,浪费了好大会儿时间。
#include<iostream >
#include<string.h>
using namespace std;
int main()
{
int cnt[141][141],dp[141],sum[141];
int N,i,j,Max;
while(cin>>N)
{
Max=-1233;
for( i=0; i<N; i++)
for(j=0; j<N; j++)
{
cin>>cnt[i][j];
}
for(int k=0; k<N; k++)
{
memset(sum,0,sizeof(sum));
memset(dp,0,sizeof(dp));
for(int m=k; m<N; m++)
{
for(int n=0; n<N; n++)
{
sum[n]+=cnt[m][n];
}
dp[0]=sum[0];
for(int p=1; p<N; p++)
{
dp[p]=max(dp[p-1]+sum[p],sum[p]);
if(dp[p]>Max)
Max=dp[p];
}
}
}
cout<<Max<<endl;
}
return 0;
}