51nod 1051 求最大子矩阵和

时间:2023-03-09 08:36:47
51nod 1051 求最大子矩阵和

题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1051

基准时间限制:2 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
一个M*N的矩阵,找到此矩阵的一个子矩阵,并且这个子矩阵的元素的和是最大的,输出这个最大的值。
例如:3*3的矩阵:
-1 3 -1
2 -1 3
-3 1 2
和最大的子矩阵是:
3 -1
-1 3
1 2
Input
第1行:M和N,中间用空格隔开(2 <= M,N <= 500)。
第2 - N + 1行:矩阵中的元素,每行M个数,中间用空格隔开。(-10^9 <= M[i] <= 10^9)
Output
输出和的最大值。如果所有数都是负数,就输出0。
Input示例
3 3
-1 3 -1
2 -1 3
-3 1 2
Output示例
7

思路:转换为最大子序列的和,遍历空间的整个状态。

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define ll long long
const int maxn=5e2+;
const int INF=0x3f3f3f3f; int mp[maxn][maxn];
ll dp[maxn]; int main()
{
int N,M;
while(scanf("%d%d",&M,&N)==)
{
for(int i=; i<=N; i++)
for(int j=; j<=M; j++)
scanf("%d",&mp[i][j]);
ll ans=-INF;
for(int i=; i<=N; i++)
{
memset(dp,,sizeof(dp));
for(int j=i; j<=N; j++)
{
for(int k=; k<=M; k++)
dp[k]+=mp[j][k];
ll num=-INF;
for(int i=; i<=M; i++)
{
num=max(num+dp[i],dp[i]);
ans=max(num,ans);
}
}
}
printf("%lld\n",ans);
}
return ;
}