To the Max
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 54338 | Accepted: 28752 |
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.
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
就是最大字段和的升级版,
从:http://www.cnblogs.com/fll/archive/2008/05/17/1201543.html 可知:
假设最大子矩阵的结果为从第r行到k行、从第i列到j列的子矩阵,如下所示(ari表示a[r][i],假设数组下标从1开始):
| a11 …… a1i ……a1j ……a1n |
| a21 …… a2i ……a2j ……a2n |
| . . . . . . . |
| . . . . . . . |
| ar1 …… ari ……arj ……arn |
| . . . . . . . |
| . . . . . . . |
| ak1 …… aki ……akj ……akn |
| . . . . . . . |
| an1 …… ani ……anj ……ann |
那么我们将从第r行到第k行的每一行中相同列的加起来,可以得到一个一维数组如下:
(ar1+……+ak1, ar2+……+ak2, ……,arn+……+akn)
由此我们可以看出最后所求的就是此一维数组的最大子断和问题,到此我们已经将问题转化为上面的已经解决了的问题了。
就是先让i从0到n遍历,然后j从i到n遍历,最后在第j行中k从0到n遍历,用一个数组分别保存每个列的各行的数字之和,就可以化为最大连续和(降维)。
复杂度为:O(n^3)
C++代码:
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxn = 102; int d[maxn][maxn]; int s[maxn]; int INF = -0x3f3f3f3f; int MaxArray(int a[],int n){ int m = INF; int tmp = -1; for(int i = 0; i < n; i++){ if(tmp > 0) tmp += a[i]; else tmp = a[i]; if(tmp > m) m = tmp; } return m; } int main(){ int n; scanf("%d",&n); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ scanf("%d",&d[i][j]); } } int ans = INF,tmp; for(int i = 0; i < n; i++){ memset(s,0,sizeof(s)); for(int j = i; j < n; j++){ for(int k = 0; k < n; k++){ s[k] += d[j][k]; } tmp = MaxArray(s,n); if(tmp > ans) ans = tmp; } } printf("%d ",ans); return 0; }