G

来源:互联网 发布:纯js实现分页 编辑:程序博客网 时间:2024/05/16 09:41

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

最大子矩阵和问题,可以转化为连续行的最大子段和,也就是相当于一个最大字段和的升级版,实际上动态规划也必定是考虑到了所有的可能情况,但只是把一些子问题的解答保存下来,其实我认为这个最大子矩阵和问题,虽然是用动态规划但实际上并没有用到先前的子问题的解答,可以想象,一个子矩阵必定是连续行连续列所构成的,我们大可以将其简化为,不相同的连续行取不相同的连续列得到的最大和。
可能这段话有些绕口,可以看看以下这个矩阵。
a11 a12 a13 a14
a21 a22 a23 a24
a31 a32 a33 a34
a41 a42 a43 a44
如果我们要取一个2*n的矩阵,显然,连续的两行有n - 1种选择,也可以看到,这个列也是连续的,例如,我们取n = 1,且从第二第三行中选取,那么取一列的话有n种选择,且要从中找到最大的和,然后n = 2时,则又有n - 1种选择,我们可以注意到一个问题,当我们增加列数的时候,选取的每一行的那一列都必须加进去,进而我们可以想到,既然增加列数,每一行的那一列的数都必须加上去,那么我们大可以直接压缩一下状态,把选取的i行压缩成为1行,然后在这一行里面求一个最大字段和。
代码如下:

#include <cstdio>#include <algorithm>#include <iostream>#include <string>#include <cstring>#define INF 0x3f3f3f3fint a[105][105];int main(){    int N;    while (scanf("%d", &N) != EOF) {        int x;        for (int i = 1; i <= N; ++i) {            for (int j = 1; j <= N; ++j) {                scanf("%d", &x);                a[i][j] = a[i - 1][j] + x;            }        }        int MAX = -INF;        for (int i = 0; i <= N; ++i) {//对每一个可能的压缩的状态求最大字段和            for (int j = i + 1; j <= N; ++j) {                int sum = 0;                for (int k = 1; k <= N; ++k) {                    sum = sum + a[j][k] - a[i][k];                    MAX = std::max(sum, MAX);                    if (sum < 0)                        sum = 0;                }            }        }        printf("%d\n", MAX);    }    return 0;}