《算法竞赛进阶指南》 To the Max--题解
To the Max
https://ac.nowcoder.com/acm/contest/1004/K
*题目描述 *
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 NN 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
integers separated by whitespace (spaces and newlines). These are the
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 * 1或更大的连续子阵列。
矩形的总和是该矩形中所有元素的总和。
在这个问题中,具有最大和的子矩形被称为最大子矩形。
例如,下列数组:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
其最大子矩形为:
9 2
-4 1
-1 8
它拥有最大和15。
输入格式
输入中将包含一个N*N的整数数组。
第一行只输入一个整数N,表示方形二维数组的大小。
从第二行开始,输入由空格和换行符隔开的N2个整数,它们即为二维数组中的N2个元素,输入顺序从二维数组的第一行开始向下逐行输入,同一行数据从左向右逐个输入。
数组中的数字会保持在[-127,127]的范围内。
输出格式
输出一个整数,代表最大子矩形的总和。
1≤N≤100。
思路:
求二维前缀和的问题(大概),先从一维开始讲:
假设给这些数:
-2 5 -3 6 7 -10
先算一个以7结尾的子序列。再看7前面的6,算以6结尾的子序列,若以6结尾的子序列的总和为正数,那么以7结尾的子序列总和就会大于以6结尾的子序列,即f(6)+7=f(7)。若以6结尾的子序列的总和是负数,那么以7结尾的子序列不如只要7这个数。
算二维的时候也是一样的。
完整C++版AC代码:
#include <iostream> #include <algorithm> #include <limits.h> using namespace std; const int N = 101; int g[N][N]; int n; int main() { cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> g[i][j]; g[i][j] += g[i - 1][j]; } } int res = INT_MIN; for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { int last = 0; for (int k = 1; k <= n; k++) { last = max(last, 0) + g[j][k] - g[i - 1][k]; res = max(last, res); } } } cout << res << endl; return 0; }