-
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.
题意:题意就是必须把矩阵某个位置替换成P,问最大子矩阵的和。
解法:弱鸡不会啊,膜了一发题解:http://blog.youkuaiyun.com/luricheng/article/details/78074046
#include <bits/stdc++.h>
using namespace std;
const int maxn = 310;
const int inf = 0x3f3f3f3f;
int n, m, p, maze[maxn][maxn], dp[maxn][2], sum[maxn], minVal[maxn];
int DP1(int n, int *sum, int p){
dp[0][0] = sum[0];
dp[0][1] = sum[0]-minVal[0]+p;
for(int i=1; i<n; i++){
dp[i][0] = max(dp[i-1][0],0)+sum[i];
dp[i][1] = max(dp[i-1][1]+sum[i], max(dp[i-1][0],0)+sum[i]-minVal[i]+p);
}
int ans=-inf;
for(int i=0; i<n; i++){
ans = max(ans, max(dp[i][0], dp[i][1]));
}
return ans;
}
int DP2(int m, int p){
int ans = -inf;
for(int i=0; i<m; i++){
int summ = 0;
int minn = inf;
for(int j=i; j<m; j++){
minn = min(minn, minVal[j]);
summ += sum[j];
if(i == 0 && j==m-1){
ans = max(ans, summ-minn+p);
}
else{
int temp = max(summ-minn+p, summ);
ans = max(ans, temp);
}
}
}
return ans;
}
int DP3(int n, int m, int p){
int ans = -inf;
for(int i=0; i<n; i++){
memset(sum, 0, sizeof(sum));
memset(minVal, 0x7f, sizeof(minVal));
for(int j=i; j<n; j++){
for(int k=0; k<m; k++){
sum[k] += maze[j][k];
minVal[k] = min(minVal[k], maze[j][k]);
}
if(i==0 && j==n-1){
ans = max(ans, DP2(m, p));
}
else{
ans = max(ans, DP1(m,sum,p));
}
}
}
return ans;
}
int main()
{
while(~scanf("%d %d %d", &n,&m,&p)){
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
scanf("%d", &maze[i][j]);
printf("%d\n", DP3(n,m,p));
}
return 0;
}
本文介绍了一个关于矩阵中寻找最大子矩阵和的问题,并提供了一种解决方案。问题要求必须将矩阵中的某一个位置替换成指定值P,然后找出替换后的最大子矩阵的和。文章通过动态规划的方法给出了具体的实现步骤。
13万+

被折叠的 条评论
为什么被折叠?



