基准时间限制: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
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=505;
int mp[maxn][maxn];
int a[maxn];
int main()
{
int n,m;
cin>>m>>n;
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>mp[i][j];
mp[i][j]+=mp[i-1][j];
}
}
for(int i=0;i<=n;i++)
{
for(int j=i;j<=n;j++)
{
int res=0;
for(int k=1;k<=m;k++)
{
res+=mp[j][k]-mp[i][k];
ans=max(res,ans);
if(res<0)
res=0;
}
}
}
printf("%d\n",ans);
}