先来一篇最大子段和和最大子矩阵和的基本知识的介绍:
https://www.cnblogs.com/aabbcc/p/6504605.html
最大子矩阵和的模板:
https://paste.ubuntu.com/15272521/
这里还有一篇用dp做的:
https://blog.csdn.net/C_13579/article/details/79927372
我的代码:
//D
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAXN 510
#define INF 0x7f7f7f7f
typedef long long LL;
LL Matrix[MAXN][MAXN];
LL Line[MAXN];
int N,M;
LL res;
LL MaxSum2(LL Line[])
{
int i;
LL ans;
LL temp;
ans=temp=0;
for(i=1;i<=M;i++)
{
if(temp>0)
temp+=Line[i];
else
temp=Line[i];
ans=max(ans,temp);
}
return ans;
}
void MaxSum()
{
int i,j,k;
res=0;
for(i=1;i<=N;i++)//枚举行
{
memset(Line,0,sizeof(Line));
for(j=i;j<=N;j++)
{
for(k=1;k<=M;k++)
Line[k]+=Matrix[j][k];
res=max(res,MaxSum2(Line));
}
}
}
int main()
{
int i,j;
while(scanf("%d%d",&M,&N)!=EOF)
{
memset(Matrix,0,sizeof(Matrix));
for(i=1;i<=N;i++)
for(j=1;j<=M;j++)
scanf("%lld",&Matrix[i][j]);
MaxSum();//求最大子矩阵和
printf("%lld\n",res);
}
return 0;
}