现在的位置: 首页 > 综合 > 正文

hdu 1024 Max Sum Plus Plus(DP&最大连续和加强版)

2019年04月12日 ⁄ 综合 ⁄ 共 1892字 ⁄ 字号 评论关闭

Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 16843    Accepted Submission(s): 5539

Problem Description
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 S1, S2, S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define
a function sum(i, j) = Si + ... + Sj (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(i1, j1) + sum(i2, j2) + sum(i3, j3) + ... + sum(im,
jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx 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(ix, jx)(1 ≤ x ≤ m) instead. ^_^

 

Input
Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 ... Sn.
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.
 

Author
JGShining(极光炫影)
 

Recommend
We have carefully selected several similar problems for you:  1074 1081 1160 1069 1058 
 题意:
给你一个长度不超过1e6的序列。要你从序列里选出不相交的m段。使得这m段的和是所有m段中最大的。
思路:
这题是最大连续和的一个扩展。状态设置很巧妙。dp[i][k]表示前i的序列中选出k段。且最后一段结尾为arr[i]的最大和。感觉比较巧妙的是加了一个限制条件结尾为arr[i]这样就可以递推了。
dp[i][k]=max(dp[i-1][k],dp[j][k-1])+arr[i]。j<i。
dp[j][k-1]为dp[1][k-1].....dp[i-1][k-1]的最大值。
由于这题m没说多大。其实也不会多大。不然这题时间完全不够。算dp时可以滚动处理。算dp[j][k-1]的时候也可以变推边算这样就省掉了一维循环。
详细见代码:
#include<algorithm>
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=1000010;
typedef long long ll;
ll dp[maxn],tp,tt,ans;
int arr[maxn];

int main()
{
    int n,m,i,k;

    while(~scanf("%d%d",&m,&n))
    {
        for(i=1;i<=n;i++)
        {
            scanf("%d",&arr[i]);
            dp[i]=0;
        }
        for(k=1;k<=m;k++)
        {
            tp=dp[k-1];
            for(i=k;i<=n;i++)
            {
                tt=dp[i];
                dp[i]=max(dp[i-1],tp)+arr[i];
                tp=max(tp,tt);
            }
        }
        ans=dp[m];
        for(i=m;i<=n;i++)
            ans=max(ans,dp[i]);
        printf("%I64d\n",ans);
    }
    return 0;
}

抱歉!评论已关闭.