题目描述:
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.
输入
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 the sum of the maximal sub-rectangle.
样例输入
4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
样例输出
15
题意理解,其实就是求最大子矩阵和的!!!!!!!(QAQ
/*挺经典的一道dp题,思路不敢想,就是先把一行的每一列压缩成这一列所能求出的最大值,然后在用求最大连续子序列的方法求出最大子矩形和。
这里用的求最大连续子序列的方法的时间复杂度是O(n),用常规方法会超时,而且如果用cin/cout,必须要关掉同步流,不然会超时!!!
*/
#include <bits/stdc++.h>
using namespace std;
int a[105][105];
int maxsum = 0,n;
void dp(int num, int r)
{
int cur_num = 0,cur_sum = 0;//记录当前高度,当前最大和。
for(int j = 1; j <= n; j++){
cur_num += a[r + num - 1][j]-a[ r - 1][j];
//找出以i为上顶,高度为high的最大矩阵,先得到s1,s2,s3.....Sn,其中,Sk=a[i+high-1][k] - a[i-1][k].
if(cur_num > cur_sum)
cur_sum = cur_num;
else if(cur_num < 0)
cur_num = 0 ;
}
if(cur_sum > maxsum)
maxsum = cur_sum; //更新最大和
}
int main(){
int temp;
while(scanf("%d",&n)!=EOF)
{
for(int i =1; i <= n; i++){
for(int j = 1; j <= n; j++){
scanf("%d",&temp);
a[i][j] = a[i - 1][j] + temp;
}
}
//这里a[i][j]表示第i行前j列元素的和。
for(int i = 1;i <= n; i++){
for(int j = 1;j <= n-i+1; j++){
dp(i,j);//以样例分析,如果高度为1 ,需要算出,以第一行到第4行为上顶的矩形和中最大的。......如果高度为4,只需要算出第1行为上顶的矩形和。
}
}
printf("%d\n",maxsum);
}
return 0;
}
)