1042 To the Max 最大子区间和 前缀和 线性DP

链接:https://ac.nowcoder.com/acm/problem/50959
来源:牛客网

题目描述

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. 

输入描述:

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 N2N^2N2 integers separated by whitespace (spaces and newlines). These are the N2N^2N2 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 the sum of the maximal sub-rectangle.
示例1

输入

复制
4
0 -2 -7 0 9 2 -6 2
-4 1 -4  1 -1

8  0 -2

输出

复制
15

题意

在一个方形区间内,找到一个子区间,区间和最大。

分析

做这题之前,先看最大连续子序列和

这题跟那题差不多,也是从左到右枚举,dp[i] = max(dp[i-1] + a[i] , a[i]);dp[i] 是到i这个位置的最大值

只不过这题要枚举上下区间,把区间内的值都加起来算作a[i] ,然后再从左往右枚举找到最大值dp[i][l][r] 表示枚举到i,区间顶部l,底部是r的最大权值

 

#include<bits/stdc++.h>
#define fo(i,l,r) for(int i = l;i<=r;i++)
using namespace std;

const int N = 101;
int g[N][N];
int n;

int main() {
cin>>n;
fo(i,1,n) {
fo(j,1,n) {
cin>>g[i][j];
g[i][j] += g[i-1][j];
}
}
int res = INT_MIN;
fo(i,1,n) {
fo(j,i,n) {
int last = 0;
fo(k,1,n) {
last = max(last,0) + g[j][k] - g[i][k];
res = max(res,last);
}
}
}
cout<<res<<endl;
}

posted @ 2022-07-14 17:28  er007  阅读(19)  评论(0编辑  收藏  举报