-
3 3 4 -100 4 4 4 -10 4 4 4 4 3 3 -1 -2 -2 -2 -2 -2 -2 -2 -2 -2
样例输出
-
24 -1
描述
Once upon a time, there was a little dog YK. One day, he went to an antique shop and was impressed by a beautiful picture. YK loved it very much.
However, YK did not have money to buy it. He begged the shopkeeper whether he could have it without spending money.
Fortunately, the shopkeeper enjoyed puzzle game. So he drew a n × m matrix on the paper with integer value ai,j in each cell. He wanted to find 4 numbers x, y, x2, and y2(x ≤ x2, y ≤ y2), so that the sum of values in the sub-matrix from (x, y) to (x2, y2) would be the largest.
To make it more interesting, the shopkeeper ordered YK to change exactly one cell's value into P, then to solve the puzzle game. (That means, YK must change one cell's value into P.)
If YK could come up with the correct answer, the shopkeeper would give the picture to YK as a prize.
YK needed your help to find the maximum sum among all possible choices.
输入
There are multiple test cases.
The first line of each case contains three integers n, m and P. (1 ≤ n, m ≤ 300, -1000 ≤ P ≤ 1000).
Then next n lines, each line contains m integers, which means ai,j (-1000 ≤ ai,j ≤ 1000).
输出
For each test, you should output the maximum sum.
题意:
给一个n*m的矩阵和一个数P,你可以将矩阵中的某个值修改成P(必须且只能修改一次),求最大子矩阵
sum[x][a][b][0]表示第x行第a列到第b列的所有数之和,中间没有数被修改
sum[x][a][b][1]表示第x行第a列到第b列的所有数之和,中间最小的那个数被修改成P
dp[x][a][b][0]表示子矩阵的最左边是第a列,最右边是第b列,最下边是第x行的最大取值,中间没有数被修改
dp[x][a][b][1]表示子矩阵的最左边是第a列,最右边是第b列,最下边是第x行的最大取值,中间一定有一个数被修改
注意:
①直接dp会超时超内存,其中dp数组很显然可以降为1维,这样就可以AC了;理论上sum[]也可以降为1维,但是比较麻烦,可以不用
②还有因为必须修改一个,所以整个矩阵不能在不修改的情况下全选!这个地方要特判,可以暴力,具体看程序
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct
{
int x;
int y;
}Res;
Res sum[302][302][302], dp[302];
int a[302][302];
int Read()
{
int x = 0, f = 1;
char ch;
ch = getchar();
while(ch<'0' || ch>'9')
{
if(ch=='-') f = -1;
ch = getchar();
}
while(ch>='0' && ch<='9')
x = x*10+ch-'0', ch = getchar();
return x*f;
}
int main(void)
{
int n, m, i, j, k, now, p, ans, sy, sx;
while(scanf("%d%d%d", &n, &m, &p)!=EOF)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
a[i][j] = Read();
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
now = a[i][j];
for(k=j;k<=m;k++)
{
now = min(now, a[i][k]);
sum[i][j][k].x = sum[i][j][k-1].x+a[i][k];
sum[i][j][k].y = sum[i][j][k].x-now+p;
}
}
}
ans = p;
for(j=1;j<=m;j++)
{
for(k=j;k<=m;k++)
{
dp[1].x = sum[1][j][k].x;
dp[1].y = sum[1][j][k].y;
if(j==1 && k==m)
ans = max(ans, dp[1].y);
else
ans = max(ans, max(dp[1].y, dp[1].x));
for(i=2;i<=n;i++)
{
sx = sum[i][j][k].x;
sy = sum[i][j][k].y;
dp[i].x = max(0, dp[i-1].x)+sx;
dp[i].y = max(sy, max(dp[i-1].x+sy, dp[i-1].y+sx));
if(j==1 && k==m)
ans = max(ans, dp[i].y);
else
ans = max(ans, max(dp[i].y, dp[i].x));
}
}
}
for(i=1;i<=n;i++)
{
now = 0;
for(j=i;j<=n;j++)
{
now += sum[j][1][m].x;
if(i==1 && j==n)
continue;
ans = max(ans, now);
}
}
printf("%d\n", ans);
}
return 0;
}