《算法竞赛进阶指南》 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;
}
全部评论

相关推荐

03-26 13:04
已编辑
电子科技大学 算法工程师
xiaowl:你这个简历“条目上”都比较有深度性,但是实际上面试官又没法很好的评估你是怎么达到很多看上去很厉害的结果的。要避免一些看上去很厉害的包装,比如高效的内存复用策略的表达,如果仅是简单的一些内存共享机制,而且面试上也没有深挖的空间,就不要这样表达。比如,工程化模式本质上可能就是定义了一些abstract class,那也就没特别多值得讲的内容。建议简历上应该侧重那些你花了大量时间和精力解决、研究的问题,不要过分追求“丰富”,而是关注在技术深入度、问题解决能力的表现上。
没有实习经历,还有机会进...
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务