基准时间限制: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<iostream>
#include<cstring>
typedef long long ll;
using namespace std;
ll sum,a[520][520],dp[520];
ll N,M,mas=-1,temp;
ll maxsub()
{
ll mas=0,t=0;
for(int i=0;i<M;i++)
{
if(t>0)t+=dp[i];
else t=dp[i];
if(t>mas)mas=t;
}
return mas;
}
int main()
{
cin>>M>>N;
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
cin>>a[i][j];
for(int i=0;i<N;i++)
{
memset(dp,0,sizeof(dp));
for(int j=i;j<N;j++)
{
for(int k=0;k<M;k++)
dp[k]+=a[j][k];
temp=maxsub();
if(temp>mas)mas=temp;
}
}
if(mas>=0)cout<<mas<<endl;
else cout<<0<<endl;
return 0;
}