原题:
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.
求出矩形中的最小和。
我们不难发现二维的数表令人非常头疼,甚至连暴力枚举所有长方形的算法都难以写出。(而且比较次数会很恐怖)。此时我们应该考虑如何能把维数降下来。一般而言,如果单对行枚举,会减少一维。于是我们把多行作一捆绑,就只剩下列了,转化成经典的最大连续和问题。
源代码:
#include <iostream>
#include <memory.h>
#include<stdio.h>
using namespace std;
int main()
{
int n;
cin>>n;
int max=-10000,thissum,maxsum;
int a[501][501];
int save[n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(int i=0;i<n;i++)
{ memset(save,0,sizeof(save));
for(int j=i;j<n;j++)
{
thissum=0,maxsum=0;
for(int k=0;k<n;k++)
{
save[k]+=a[j][k];//此处j自然利用,千万别加多余的循环。
}
for(int x=0;x<n;x++)
{
thissum+=save[x];
if(thissum>maxsum)maxsum=thissum;
else if(thissum<0)thissum=0;
}
max=max<maxsum?maxsum:max;
}
}
cout<<max<<endl;
return 0;
}