Problem Description
Given atwo-dimensional array of positive and negative integers, a sub-rectangle is anycontiguous 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. Inthis problem the sub-rectangle with the largest sum is referred to as themaximal 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 consistsof an N x N array of integers. The input begins with a single positive integerN 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 secondrow, left to right, etc. N may be as large as 100. The numbers in the arraywill be in the range [-127,127].
Output
Output the sum ofthe 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
求最大子矩阵的和。这道题里面没有这样的例子,全是负数的情况,输出0或者最大的一个负数都可以。
转移方程:dp[i][j][k] = max(sum(num[i][j]---num[i][k]) , dp[i-1][j][k] + sum(num[i][j]---num[i][k]))
dp[i][j][k]表示的是矩阵最后一行为第i行第j个元素到第k个元素最大值。这个矩阵只跟其上一层为最后一行的矩阵有关系。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
int num[110][110] ,n ,m;
int dp[110][110][110];//dp[i][j][k]表示矩阵最后一行为第i行第j个元素到第k个元素最大值
int main()
{
int sum;
while(~scanf("%d",&n))
{
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
scanf("%d",&num[i][j]);
}
}
m = INT_MIN;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
for(int k = j;k <= n;k++)
{
sum = 0;
for(int s = j;s <= k;s++)
{
sum += num[i][s];
}
dp[i][j][k] = sum;
if(dp[i][j][k] < dp[i - 1][j][k] + sum)
{
dp[i][j][k] = dp[i - 1][j][k] + sum;
}
if(m < dp[i][j][k])
{
m = dp[i][j][k];
}
}
}
}
printf("%d\n",m);
}
return 0;
}
求第j到k个元素的和也可以继续用dp的思想。同时,因为从第一行依次往下,且每次只会用到当前行和前一行。因此,只用记录前一行j到k之和就可以了。
sum用来保存当前行j到k之和,sum_front记录前一行j到k之和。dp用来记录当前行为最后一行j到k的矩阵的最大值。
这个做法较上一个做法减少了算j到k之和的时间,没有暴力计算。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
int num[110][110] ,n ,m;
int dp[110][110] ,sum[110][110];
int main()
{
int sum_front;
while(~scanf("%d",&n))
{
memset(dp,0,sizeof(dp));
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
scanf("%d",&num[i][j]);
}
}
m = 0;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
for(int k = j;k <= n;k++)
{
sum_front = dp[j][k];
sum[j][k] = sum[j][k-1] + num[i][k];
dp[j][k] = sum[j][k];
if(0 < sum_front)
{
dp[j][k] += sum_front;
}
if(m < dp[j][k])
{
m = dp[j][k];
}
}
}
}
printf("%d\n",m);
}
return 0;
}