Maximum Sum UVA - 108(二维子矩阵最大和)链接
A problem that is simple to solve in one dimension is often much more difficult to solve in more than
one dimension. Consider satisfying a boolean expression in conjunctive normal form in which each
conjunct consists of exactly 3 disjuncts. This problem (3-SAT) is NP-complete. The problem 2-SAT
is solved quite efficiently, however. In contrast, some problems belong to the same complexity class
regardless of the dimensionality of the problem.
Given a 2-dimensional array of positive and negative integers, find the sub-rectangle with the largest
sum. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the subrectangle
with the largest sum is referred to as the maximal sub-rectangle.
A sub-rectangle is any contiguous sub-array of size 1 × 1 or greater located within the whole array.
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-hand corner:
9 2
−4 1
−1 8
and has the 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 N2
integers separated by white-space (newlines and spaces).
These N2
integers make up the array in row-major order (i.e., all numbers on the first row, left-to-right,
then all numbers on 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 output is 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
翻译
在一个维度中,一个简单的问题往往在多个维度中更难解决。考虑满足连接正规形式的布尔表达式,其中每个连接正好由3个析取组成。这个问题(3-sat)是NP完全问题。然而,2-SAT问题得到了相当有效的解决。相比之下,有些问题属于同一个复杂度类,与问题的维度无关。
给定一个由正整数和负整数组成的二维数组,找出最大的子矩形
总和。矩形的和是该矩形中所有元素的和。在这个问题中,子面角
和最大的被称为最大的子矩形。
子矩形是位于整个数组中大小为1×1或更大的任何连续子数组。
例如,数组的最大子矩形:
0−2−7 0
9 2-6 2
-4 1-4 1
-1 8 0-2
位于左下角:
9月2日
-4 1个
-18个
总共有15个。
输入
输入由n×n整数数组组成。
输入以一行上的一个正整数n开始,该整数本身指示平方的大小。
二维数组。然后是n2
用空格分隔的整数(换行符和空格)。
这些氮气
整数按行主顺序组成数组(即第一行的所有数字,从左到右,
然后是第二行的所有数字,从左到右,等等)。n可以大到100。中的数字
数组将在范围[-127、127]内。
输出
输出是最大子矩形的和。
思路
和一维的求最大和子序列有点类似,不过这是二维的。直接暴力会超时,把二维转化为一维,利用连续子序列求最大和。
(还看到一种写法,但是不是特别理解:枚举行区间,求出每列的和,再用d[i]=max(d[i-1]+sum[i],sum[i])动态规划公式,即可求出最大子矩阵和。)
代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int n,i,j,k,a[200