hdu 1024 Max Sum Plus Plus(经典dp) 有点小bug?

来源:互联网 发布:windows 连接ecs 编辑:程序博客网 时间:2024/06/05 13:34

Max Sum Plus Plus

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


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 ≤ jxor 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 32 6 -1 4 -2 3 -2 3
 

Sample Output
68
Hint
Huge input, scanf and dynamic programming is recommended.
 


     题目大意:设输入的数组为a[1...n],从中找出m个连续的段,使得这几个段的和为最大。
    解题思路:dp[i][j]表示前j个数中取i个段的和的最大值,其中最后一个段包含a[j]。当然我们需要开的数组可能会爆内存,dp[10^6][m],m给多大我们是不知道的。如果是10的话根本开不了。我们先找到状态转移方程:
dp[i][j]=max{dp[i][j-1],max{dp[i-1][t]}} +a[j]   1=<t<=j-1

我们计算dp[i][j]的时候只会用到dp[i-1][t]中的最大值,因此我们可以用一个last数组将他们保存。
于是状态转移方程转化为:
dp[j]=max(dp[j-1],last[j-1])+a[j].
当然last需要随时更新。

但是分析数据
应该是要用long long的?最大值是3*10^10,但是会超时,纠结了一个小时
求路过的大神帮忙看看。。

题目地址:Max Sum Plus Plus

AC代码:
#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int maxn = 1000005;//dp[i][j]=max(dp[i][j-1],dp[i-1][t])+a[j]  (1<=t<=j-1)int a[maxn];int dp[maxn];int last[maxn];int main(){    int n,m;    int i,j;    while(~scanf("%d%d",&m,&n))    {        for(i=1;i<=n;i++)            scanf("%d",&a[i]);        for(i=0;i<=1e6;i++)            dp[i]=last[i]=0;                int ma;        for(i=1;i<=m;i++)        {            ma=-1e9;   //更新dp[i-1][t](1<=t<=j-1)即last的最大值            for(j=i;j<=n;j++)            {                if(dp[j-1]>last[j-1]) dp[j]=dp[j-1]+a[j];                else dp[j]=last[j-1]+a[j];                last[j-1]=ma;                if(dp[j]>ma) ma=dp[j];            }        }        printf("%d\n",ma);    }    return 0;}/*1 3 1 2 32 6 -1 4 -2 3 -2 3*/



0 0
原创粉丝点击