To the Max
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 51817 | Accepted: 27379 |
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.
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
一、原题地址
二、大致题意
求给定大小的矩阵中的最大矩阵和。
三、思路
求出矩阵每行的前缀和,记作dp[i][j],那么dp[i][x]-dp[i][y]就是矩阵在第i行上第y列到第x列的和。这样就把问题转化为了求最大的子序列和。我们只要枚举dp[i][x]-dp[i][y]中的x和y就可以了。
四、代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<stack>
using namespace std;
const int inf = 0x3f3f3f3f;
#define LL long long int
long long gcd(long long a, long long b) { return a == 0 ? b : gcd(b % a, a); }
int a[105][105], dp[105][105], sum[105];
int n;
int main()
{
memset(dp, 0, sizeof(dp));
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
scanf("%d", &a[i][j]);
dp[i][j] = dp[i][j - 1] + a[i][j];
}
}
int ans = -inf;
for (int l = 1; l <= n; l++)
{
for (int r = l ; r <= n; r++)
{
sum[0] = 0;
for (int k = 1; k <= n; k++)
{
sum[k] = dp[k][r] - dp[k][l-1];
}
for (int k = 1; k <= n; k++)
{
if (sum[k - 1] >= 0)sum[k] += sum[k - 1];
else sum[k] = sum[k];
ans = max(ans, sum[k]);
}
}
}
printf("%d\n", ans);
getchar();
getchar();
}