Problem Description
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1 x 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.
Input
The input consists of an N x 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
题意:就是求最大子矩阵的和
思路:先压缩矩阵,把二维数组压缩成一维数组,转换为求一个序列的最大连续和
压缩矩阵:
假设有一个矩阵:
-5 6 4
1 -2 6
2 1 -3
如何对它进行压缩呢,其实不难,这边我做一个类比,如果我们把每一行(或者一列)看做一个数,这里也就是可以看做三个数a,b,c。然后将这三个相邻数的进行不同的组合,每一个新的组合都视为一个新的数,这就是进行压缩处理,例如a,b,c可以组合为{[a],[ab],[abc],[b],[bc],[c]},而矩阵压缩也类似。
我们先设置一个变量max用于保存压缩后的一维数组的最大子序列和。
第一次我们取第一行:(第一轮)
-5 6 4
则其最大子序列和为10,max=10。
第二次取第一二行:
-5 6 4
1 -2 6
注意现在开始是矩阵压缩的精髓,我们将每一列的数进行相加,将多行变为一行。
第一列:-5+1=-4
第二列:6+(-2)=4
第三列:4+6=10
所以压缩后的一维数组为:
-4 4 10
则其最大子序列和为14,max=14。
第三次取第一二三行:
-5 6 4
1 -2 6
2 1 -3
对每一列进行压缩:
第一列:-5+1+2=-2
第二列:6+(-2)+1=5
第三列:4+6+(-3)=7
所以压缩后的一维数组为:
-2 5 7
则其最大子序列和为12,max=14。
第四次取第二行:(也就是第二轮了)
1 -2 6
则其最大子序列和为6,max=14。
第五次取第二三行:
1 -2 6
2 1 -3
对每一列进行压缩:
第一列:1+2=3
第二列:-2+1=-1
第三列:6+(-3)=3
所以压缩后的一维数组为:
3 -1 3
则其最大子序列和为5,max=14。
第六次取第三行:(第三轮)
2 1 -3
则其最大子序列和为3,max=14。
最后求得这个矩阵最大的子矩阵和为14
也就是第一二行的三四列
6 4
-2 6
显而易见,answer就是每一轮中最大的那个
代码中有详细注释
(例子参考了:https://blog.csdn.net/HuiSeKongHuan/article/details/79329436这篇博客,java写的)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a[200][200],b[200],n;
void sum_col(int x,int y)
{
for(int i=0; i<n; i++)//第i列的和
{
for(int j=x; j<=y; j++)
b[i]+=a[j][i];
}
}
int calc()//求最大连续子序列的和(b是一维数组)
{
int sum=-200,ans=-200;
for(int i=0;i<n;i++)
{
if(sum<0) sum=b[i];
else sum+=b[i];
ans=max(ans,sum);
}
return ans;
}
int main()
{
while(cin>>n)
{
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin>>a[i][j];
//还可以利用前缀和
int ans=-200;//题目中是-127
for(int i=0; i<n; i++) //总共枚举n伦,从第一层开始,第二层开始,第三层.....一直到最后一层
{
for(int j=i; j<n; j++) //从第i层到第j层
{
memset(b,0,sizeof (b));
sum_col(i,j);//和已经存储在b数组中
ans=max(ans,calc());//对b求最大连续子序列的和
}
}
cout<<ans<<endl;
}
return 0;
}