To The Max

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10920    Accepted Submission(s): 5229


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.
 

 

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
 
实质上是最大子段和问题,最大子矩阵我们将其所有的行都枚举出来,然后将其合并成一行,然后就可以用最大连续子段和求最大值,得到最大子矩阵。
 
最大子段和:
    令b[j]表示以位置 j 为终点的所有子区间中和最大的一个
    子问题:如j为终点的最大子区间包含了位置j-1,则以j-1为终点的最大子区间必然包括在其中
    如果b[j-1] >0, 那么显然b[j] = b[j-1] + a[j],用之前最大的一个加上a[j]即可,因为a[j]必须包含
    如果b[j-1]<=0,那么b[j] = a[j] ,因为既然最大,前面的负数必然不能使你更大
   状态转移方程 dp[j] = max(dp[j-1]+a[j],a[j])(0<j<=n)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include <string.h>
#include <math.h>
using namespace std;
const int N = 101;
int mp[N][N],b[N];
int n;

int getMax()
{
    int t = 0,mx = -1;
    int dp[N+1]= {0};
    for(int i=1; i<=n; i++)///从1开始枚举
    {
        if(dp[i-1]>0) dp[i] = dp[i-1]+b[i-1];
        else dp[i]=b[i-1];
        mx = max(mx,dp[i]);
    }
    return mx;
}
int solve()
{
    int mx = -1;
    for(int i=0; i<n; i++)
    {
        for(int j=i; j<n; j++)
        {
            memset(b,0,sizeof(b));
            for(int k=0; k<n; k++)
                for(int l=i; l<=j; l++)
                    b[k]+=mp[l][k];
            mx = max(mx,getMax());
        }
    }
    return mx;
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<n; j++)
                scanf("%d",&mp[i][j]);
        }
        int mx = solve();
        printf("%d\n",mx);
    }
    return 0;
}