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+5;
const int INF=0x3f3f3f3f;

int mp[maxn][maxn];
ll dp[maxn];

int main()
{
    int N,M;
    while(scanf("%d%d",&M,&N)==2)
    {
        for(int i=1; i<=N; i++)
            for(int j=1; j<=M; j++)
                scanf("%d",&mp[i][j]);
        ll ans=-INF;
        for(int i=1; i<=N; i++)
        {
            memset(dp,0,sizeof(dp));
            for(int j=i; j<=N; j++)
            {
                for(int k=1; k<=M; k++)
                    dp[k]+=mp[j][k];
                ll num=-INF;
                for(int i=1; i<=M; i++)
                {
                    num=max(num+dp[i],dp[i]);
                    ans=max(num,ans);
                }
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/a-clown/p/6034120.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值