HDU-1024 Max Sum Plus Plus(动态规划+滚动数组)

题目描述

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(i 2, 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. _

输入格式

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 the maximal summation described above in one line.

样例输入

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

样例输出

6
8

题意:

给定长度为N的序列S。定义sum(i , j) = s[i] + … + s[j]。给定m,求最大的m段连续序列和:
sum(i 1, j 1) + … + sum(i m, j m), 且没有ix <= iy <=jx;
即在n个数中选出m组数, 每组数连续且不能相交, 求其所有组的最大和。





题解:

  • 定义状态:dp[i][j]为以第j个数结尾的分为i份的最大。
  • 状态转移:一个以a[j]结尾的“i份最大划分组”,要么将是将a[j]加入a[j-1]结尾的“i份划分组”,即dp[i][j-1]+a[j]; 要么是a[j]单独自成一组,与前面的“i-1份最大划分组”结合,即max(dp[i-1][k])+a[j] 其中k < j
  • 状态方程: d p [ i ] [ j ] = max ( d p [ i ] [ j 1 ] + a [ j ] ,   max ( d p [ i 1 ] [ k ] ) + a [ j ] ) dp[i][j] = \max(dp[i][j-1]+a[j],\ \max(dp[i-1][k]) + a[j])
  • n2的空间复杂度对于1e6是明显超限的。需要优化。
    因为我们只需要划分成m份的最大和,中间的过程都不需要(和背包问题类似),所以我们可以只用一维数组滚动就行了。
  • 对于dp[i-1][k]:上一层划分的之前的最大值,可以用额外的数组lastmax来存储,在滚动时维护。
  • 在m次循环后,dp[n]数组中的最大值即为最后所求答案
#include<bits/stdc++.h>
using namespace std;
#define maxn 1000005
#define inf 0x3f3f3f3f

int dp[maxn], a[maxn], lastmax[maxn]; 

int main()
{
    int m, n;
    while(scanf("%d %d",&m,&n)!=EOF)
    {
        memset(dp, 0, sizeof dp);
        memset(lastmax, 0, sizeof lastmax); 
        int maxx;
        for(int i=1; i<=n; i++)
            scanf("%d",&a[i]);
        for(int i=1; i<=m; i++)  //在第i层循环中,lastmax[j]是指第j个元素前的划分成i-1份的最大的sum
        {
            maxx = -inf;
            for(int j=i; j<=n; j++)  //要分成i组则至少需要i个数,所以j从i开始循环
            {
                dp[j] = max(dp[j-1]+a[j], lastmax[j-1]+a[j]);
                lastmax[j-1] = maxx; //只能更新以前一个数结尾的lastmax(因为当前数的lastmax要在下一轮迭代中要用来更新dp
                //所以还必须在当前层dp更新完后更新)
                maxx = max(dp[j], maxx); //该语句不可与上行语句交换位置
            }
        }
        cout << maxx << endl; //此时maxx存储的即为最后一次划分(m份)的最大值
    }
    return 0;
}
发布了35 篇原创文章 · 获赞 15 · 访问量 1117

猜你喜欢

转载自blog.csdn.net/irimsky/article/details/99656576
今日推荐