#1580 : 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.
输入
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
【题意】给你一个矩阵,要求你必须选择一个数把它换成p,然后再求一个最大子矩阵和。
【分析】考虑到普通求最大子矩阵的方法,先枚举上下行,然后对每一列求和再dp,如果我们要通过修改某个值
来获得更大的ans时,那么换掉的肯定是这个子矩阵中的最小值,那么我们枚举上下行时,dp[i][0/1]表示以第i
列结尾的矩阵1:已经修改过了/0:还没修改 获得的最大子矩阵值,然后分情况DP就行了。有一种情况就是当你的
最大值是取完所有矩阵而且不修改值时,当前最大值 不与ans更新,因为题目要求必须修改。#include <bits/stdc++.h> #define inf 0x3f3f3f3f #define met(a,b) memset(a,b,sizeof a) #define pb push_back #define mp make_pair #define rep(i,l,r) for(int i=(l);i<=(r);++i) #define inf 0x3f3f3f3f using namespace std; typedef long long ll; const int N = 3e2+50;; const int M = 255; const int mod = 19260817; const int mo=123; const double pi= acos(-1.0); typedef pair<int,int>pii; int n,t,cas; int a[N][N],m,p,sum[N]; int mn[N],dp[N][2],len[N]; bool flag; int solve(){ dp[0][0]=dp[0][1]=0; int ret=-inf;len[0]=0; for(int i=1;i<=m;i++){ if(dp[i-1][0]>0){ dp[i][0]=dp[i-1][0]+sum[i]; len[i]=len[i-1]+1; } else { dp[i][0]=sum[i]; len[i]=1; } if(i==1){ dp[i][1]=sum[1]-mn[1]+p; } else { dp[i][1]=max(sum[i]-mn[i]+p,dp[i-1][0]+sum[i]-mn[i]+p); dp[i][1]=max(dp[i][1],dp[i-1][1]+sum[i]); } ret=max(ret,dp[i][1]); if(flag&&len[i]==m)continue; ret=max(ret,dp[i][0]); } return ret; } int main(){ while(~scanf("%d%d%d",&n,&m,&p)){ for(int i = 1; i <= n; ++i){ for(int j = 1; j <= m; ++j){ scanf("%d", &a[i][j]); } } int ans = -inf; for(int i = 1; i <= n; ++i){ met(sum,0);met(mn,inf);flag=false; for(int j = i; j <=n; ++j){ for(int k = 1; k <= m; ++k){ sum[k]+=a[j][k]; mn[k]=min(mn[k],a[j][k]); } if(i==1&&j==n)flag=true; ans=max(ans,solve()); } } printf("%d ",ans); } return 0; }