Ural-1146Maximum Sum-最大子矩阵
Time limit: 0.5 second | Memory limit: 64 MB |
---|
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 sub-rectangle 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 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 N 2 integers separated by white-space (newlines and spaces). These N 2 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 | output |
---|---|
4 | 15 |
0 -2 -7 0 | |
9 2 -6 2 | |
-4 1 -4 1 | |
-1 8 0 -2 |
最大子矩阵和:以前做过一维的最大连续和,现在换成二维,而思路还是类似,不过要提前将二维的转化为一维,处理起来就是很方便,求出每一行的前缀和,然后枚举列,即可求出最大子矩阵和。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int a[110][110];
int ans ;
int main()
{
while(~scanf("%d",&n))
{
memset(a,0,sizeof(a));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);//前缀和
a[i][j]+=a[i][j-1];
}
}
ans = -10000000;
for(int i=1;i<=n;i++)
{
for(int j=i;j<=n;j++)//枚举列每一次求第i列到第j列之间的最大和
{
int Max = -10000000;
int sum = 0;
for(int k=1;k<=n;k++)
{
sum+=(a[k][j]-a[k][i-1]);
Max = max(Max,sum);
if(sum<0)
{
sum = 0;
}
}
ans = max(ans,Max);
}
}
printf("%d\n",ans);
}
return 0;
}