Max Sum Plus Plus (dp+滚动数组)

Now I think you have got an AC in Ignatius.L's "Max Sum" problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem. 

Given a consecutive number sequence S 1, S 2, S 3, S 4 ... S x, ... S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x≤ 32767). We define a function sum(i, j) = S i + ... + S j (1 ≤ i ≤ j ≤ n). 

Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i 1, j 1) + sum(i2, j 2) + sum(i 3, j 3) + ... + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x ≤ j y ≤ j x is not allowed). 

But I`m lazy, I don't want to write a special-judge module, so you don't have to output m pairs of i and j, just output the maximal summation of sum(i x, j x)(1 ≤ x ≤ m) instead. ^_^ 

Input

Each test case will begin with two integers m and n, followed by n integers S 1, S 2, S 3 ... S n
Process to the end of file. 

Output

Output the maximal summation described above in one line. 

Sample Input

1 3 1 2 3
2 6 -1 4 -2 3 -2 3

Sample Output

6
8


        
  

Hint

Huge input, scanf and dynamic programming is recommended.

        
 题意:求分成m段的最大和

思路:设dp[i][j]表示前j个数(包括第j个数),分成i段的最大和,那么它的最优子结构可能来自两部分,第一部分是当第j个数单独作为1段,第二部分是j和前面的连成一部分。那么dp[i][j]=max(dp[i-1][j]+a[j],dp[i-1][k]+a[j])(k>=i-1&&k<=j-1)

再设g[i][j]表示前j个数,分成i段的最大和(此时第j个数可能包括也可能不包括)

g[i][j]=max(g[i][j-1],dp[i][j]);

扫描二维码关注公众号,回复: 2633071 查看本文章

通过g函数的定义,可以将dp的递推式优化为dp[i][j]=max(dp[i][j-1],g[i-1][j-1])+a[j];

g[i-1][j-1]表示的是,第j个单独成段,去掉第j个后,剩下的i-1段由剩下的j-1个数组成;

滚动数组:因为i从1到m,要计算dp[i][j]=max(dp[i][j-1],g[i-1][j-1])+a[j],我们只需要知道它的前一轮数就行,而g[i-1]是前一轮推出来的,所以可以把i的数组直接滚动了。(能不能滚动,主要是看计算当前状态需要的之前状态是什么,如果只需要前一轮的状态,那么只要保证在需要它之前,它还没有被更新就行)

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
#define inf 0x3f3f3f3f
int m,n;
int a[maxn];
int dp[maxn];
int g[maxn];
int main(int argc, char const *argv[])
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        memset(dp,0,sizeof(dp));
        memset(g,0,sizeof(g));
        int mm;
        for(int i=1;i<=m;i++)
        {
            mm=-inf;
            for(int j=i;j<=n;j++)
            {
                dp[j]=max(dp[j-1]+a[j],g[j-1]+a[j]);
                g[j-1]=mm;
                mm=max(mm,dp[j]);
            }
        }
        cout<<mm<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/81302548