To The Max
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6512 Accepted Submission(s): 3117
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这题可以(On^4)暴力过,但是这是数据较小,如果数据大就会TE了,所以我是用矩阵压缩和求最大连续子序列方法/*子矩阵必定也是由行和列组成, 如上这个矩阵 它的行的组合有 1,1-2,1-3,1-4,2,2-3,2-4,3,3-4,4 无非这10种组合 这样我们就可以将行进行压缩 比如说:1-2 我们将1,2行数据进行压缩 及进行合并 0 -2 -7 0 + 9 2 -6 2 ------------- 9 0 -13 2 那么这样我们就可以通过求最大连续子串和的思想求其最大值为9 再看:2-4这个组合 9 2 -6 2 -4 1 -4 1 + -1 8 0 -2 ---------------- 4 11 -10 1 所以它的最大和为15 这样通过压缩行 即将这个矩形的宽变为1 可以迅速的求出子矩阵的值 并求出最大值 因为求最大连续子串和思想是线性的 复杂度为O(N) 所以可以快速求出压缩后矩阵的和! */ #include<iostream> #include<cstring> #include<string> #include<cstdio> #include<cstdlib> #include<cmath> #include<algorithm> #include<queue> #include<stack> #include<iomanip> #include<map> #include<set> const int MAX=101; int matrix[MAX][MAX]; int DP[MAX][MAX]; using namespace std; int main() { int n,i,j,Max,maxn,sum; while(cin>>n) { for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { cin>>matrix[i][j]; } } memset(DP,0,sizeof(DP)); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { DP[j][i]=DP[j][i-1]+matrix[i][j];//dp[j][i]代表第j列从第1行开始的数累加到到第i行的和 } } Max=0; for(i=1;i<=n;i++) { for(j=i;j<=n;j++) { maxn=0; sum=0; for(int k=1;k<=n;k++) { sum+=DP[k][j]-DP[k][i-1];//表示第k列从第i行到第j行数字之和 if(sum>0) { if(sum>maxn) maxn=sum; } else sum=0; } if(maxn>Max) Max=maxn; } } cout<<Max<<endl; } return 0; }