hihocoder 1580 Matrix(北京icpc2017网络赛)

#1580 : Matrix


时间限制:1000ms

单点时限:1000ms

内存限制:256MB

描述

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.

样例输入
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
题意:给你一个n × m的矩阵,你必须把其中一个数变成p,然后找一个子矩阵,
子矩阵的所有数之和最大。
思路:对于一个给定的矩阵,我们要使它的和最大,那一定是把这个矩阵中最小的数改成p,所以我们需要维护一个最小值,二维的最小值很难维护,所以我们维护的是一维的。
做法和最大子区间和一样,i,j枚举的是上下边界,k枚举列。
dp[k][0]表示前k列没有改数字得到的最大矩阵和。
dp[k][1]表示前k列修改一个数字得到的最大矩阵和。
mp[k]表示的是在【i,j】区间内第k列的最小值。
dp[k][0]=max(dp[k-1][0],0)+sum[k];
dp[k][1]=max(dp[k-1][1]+sum[k],max(dp[k-1][0],0)+sum[k]-mp[k]+p);
#include<iostream>
#include<cmath>
#include<cstring> 
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,p,ans,a[500][500],sum[500],mp[500],dp[500][2];
int main()
{    
	while(~scanf("%d%d%d",&n,&m,&p))
	  {
	  	int ans=-1000000000,ms=0;
	  	for(int i=1;i<=n;i++)
		   for(int j=1;j<=m;j++) scanf("%d",&a[i][j]),ms+=a[i][j];
		for(int i=1;i<=n;i++)
		   {
		   	dp[0][0]=0;
		   	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) mp[k]=a[j][k]; else mp[k]=min(mp[k],a[j][k]);
			    	   	dp[k][0]=max(dp[k-1][0],0)+sum[k];
			    	   	if(i==1&&j==n&&k==m&&dp[k][0]==ms) ; else ans=max(ans,dp[k][0]);
			    	   	//如果不是整个矩阵的话,可以修改矩阵外的任意一点使其达到题目要求,注意一定要是dp[k][0]==ms,保证是整个矩阵。 
			    	   	if(k>1) dp[k][1]=max(dp[k-1][1]+sum[k],max(dp[k-1][0],0)+sum[k]-mp[k]+p);
			    	   	else dp[k][1]=sum[k]-mp[k]+p;
			    	   	ans=max(ans,dp[k][1]);
			           }
		            } 
		   } 
	  printf("%d\n",ans);
	  }
}

posted @ 2018-05-01 14:14  The-Pines-of-Star  阅读(144)  评论(0编辑  收藏  举报