【dp】51nod 1052 最大M子段和

来源:互联网 发布:淘宝宝贝收藏 编辑:程序博客网 时间:2024/06/05 18:32
Link:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1052

#include <bits/stdc++.h>using namespace std;typedef long long LL;const int N = 5e3+5;const LL INF = 0x3f3f3f3f;LL a[N];LL dp[N],pre[N];int main(){    int n,m;    scanf("%d%d",&n,&m);    int num = 0;    LL ans = 0;    for(int i = 1; i <= n; i++){        scanf("%lld",&a[i]);        if(a[i] > 0)        {            ans += a[i];            num++;        }    }    if(num <= m)        printf("%lld\n",ans);    else{        for(int i = 1; i <= m; i++){            ans = -INF;            for(int j = 1; j <= n; j++)            {                if(j == 1)  dp[j] = a[j];                else    dp[j] = max(pre[j-1],dp[j-1])+a[j];                pre[j-1] = ans;                ans = max(ans,dp[j]);                //printf("%lld ",dp[j]);            }            pre[n] = ans;            //puts("");        }        printf("%lld\n",pre[n]);    }    return 0;}


原创粉丝点击