POJ 1050
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.
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
Source
题意:求最大子矩阵
思路:确定一个矩阵,暴力思路,枚举起始行,终点行,起始列,终点列,需要四重循环,会超时。
可以利用前缀和的方法减少一维。
若最优解在i到j行之间,求每列的前缀和,则题目变成一维的最大的连续子区间问题。
例如:若最优解在【2,3】行
9 2 -6 2
-4 1 -4 1
求出每列的和
5 3 -10 3 ,则问题变成了求5,3,-10,3的连续最大子区间的值。
#include<bits/stdc++.h>
using namespace std;
int a[200][200],n,sumb[200];
int maxsum(){//计算最大的子段
int dp,maxx;
dp=maxx=-200;
for(int i=1; i<=n; i++){
dp=max(sumb[i],sumb[i]+dp);
maxx=max(maxx,dp);
}
return maxx;
}
//dp[i]表示以i结尾的最大区间 dp[i]=max(a[i],a[i]+dp[i-1])
//因为只用了a[i],dp[i-1]更新,所以可以滚动使用,dp=max(a[i],a[i]+dp),
//空间复杂度为O(1)
int main(){
cin>>n;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
cin>>a[i][j];
}
}
int maxx2=-200,maxx=-200,i,j;
for(i=1; i<=n; i++){
memset(sumb,0,sizeof(sumb));
for(j=i; j<=n; j++){//控制行
for(int k=1; k<=n; k++){//遍历列 ,计算每列在一定行范围内的和
sumb[k]+=a[j][k];
}
maxx=max(maxx,maxsum());//maxx是局部行的最大解
maxx2=max(maxx2,maxx);//整个问题的最大解
}
}
cout<<maxx2<<endl;
return 0;
}
/*假如最优解在第i行和第j行之间,那么只要把所有列的和求出来,
那么问题就转化为求一维数组的最大的连续区间的问题。
*/