HihoCoder1580 Matrix (DP)

                                                       Matrix

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.

Input

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).

Output

For each test, you should output the maximum sum.

Sample Input

3 3 4
-100 4 4
4 -10 4
4 4 4
3 3 -1
-2 -2 -2
-2 -2 -2
-2 -2 -2

Sample Output

24
-1

 

一、原题地址

点我传送

 

二、大致题意

可以将矩阵中的一个元素替换成给定的元素P,求一个最大子矩阵和。

 

三、思路

降维求子矩阵和,再多开一维dp[ ][1/0 ]。1表示使用了替换,0表示没使用替换。

 

四、代码

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int inf = 0x3f3f3f3f;



int n, m, P;
int a[500][500],sum[500],minn[500],dp[500][2];
int main()
{
	while (scanf("%d %d %d", &n, &m, &P) != EOF)
	{
		int Zong = 0;
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= m; j++)
				scanf("%d", &a[i][j]),Zong+=a[i][j];
		memset(dp, 0, sizeof(dp));
		int ans = -inf;
		for (int i = 1; i <= n; i++)
		{
			memset(sum, 0, sizeof(sum));
			for (int j = i; j <= n; j++)
			{
				for (int k = 1; k <= m; k++)
				{
					sum[k] += a[j][k];
					if (i == j)minn[k] = a[j][k];
					else minn[k] = min(minn[k], a[j][k]);

					dp[k][0] = max(0, dp[k - 1][0]) + sum[k];
					if (i == 1 && j == n&&k == m&&dp[k][0] == Zong); else ans = max(ans, dp[k][0]);
					if(k>1)
						dp[k][1] = max(dp[k - 1][1] + sum[k], 
							max(dp[k-1][0],0) + sum[k] - minn[k] + P);
					else dp[k][1] = sum[k] - minn[k] + P;
					ans = max(ans, dp[k][1]);
				}
			}
		}
		printf("%d\n", ans);
	}
	getchar();
	getchar();
}

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值