To the Max 二维dp(一维的变形)

时间:2023-03-09 05:54:43
To the Max  二维dp(一维的变形)

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. 

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

题解:

看起来很难做的题目,但他让我们想起 最大字段和,但那个是一维的。

那怎么转化二维为1维呢?

当然是枚举了。

分别枚举第 i 行到第 j 行 ,这里的复杂度为O(n^2),然后在用字段和遍历一遍,所以总的时间复杂度为O(n^3) 考虑到n不大,可行。

有一个问题是怎么最快求第k列中,第 i 行道第 j 行的和,我们采用前缀和的方式。

由于网上多是行前缀和,这里贴一个列前缀和的代码

#include<stdio.h>
#include<cmath>
#include<iostream>
#define INF 0x3f3f3f3f
#define me(a,b) memset(a,b,sizeof(a))
#define N 102
typedef long long ll;
using namespace std; int n,a[N][N],dp[N][N],t,sum,ans; int main()
{
//freopen("input.txt","r",stdin);
cin>>n;
for(int i=;i<=n;i++)
{
for(int j=;j<=n;j++)
{
cin>>t;
a[i][j]=a[i][j-]+t;//记录前缀和
}
}
for(int i=;i<=n;i++)
{
for(int j=i;j<=n;j++) //枚举,第i列道第j列
{
sum=;
for(int k=;k<=n;k++)//最大子序列遍历一遍
{
int t=a[k][j]-a[k][i-];//t代表: 第k行中,第 i 列到第 j 列的和
sum+=t;
sum=sum<?:sum; //<0则置为0
if(sum>ans)
ans=sum;
}
}
}
cout<<ans; }