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
#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); } }