杭电OJ——1024 Max Sum Plus Plus

原文地址:http://blog.sina.com.cn/s/blog_677a3eb30100jxqa.html

Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4521 Accepted Submission(s): 1476

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(极光炫影)

思路:

dp[i][j]表示前j个元素分成i段的最优解,同时这个最优解是由a[j]元素结束的。
dp[i][j]=max{f[i][j-1]+a[j],f[i-1][k]+a[j]}
i-1<=k<j,i<=j<=n-m+i
其中j的上下界的确定比较麻烦。现在分别解释上界和下界:
上界:dp[i][j]中,如果j=i-1,意思就是在前面i-1个元素中分成i段,这个是不可能实现的。
下界:如果m=n=4,这时dp[2][4]求出来了,意思是前面的四个元素分成了两段,当是还有两段要分,
      所以求出这个是没有意义的。当然求出来也不会影响结果,只是这样时间复杂度就提高了。
这是其中一个特例的状态转移表 m=4,n=6-1 4 -2 3 -2 3

杭电OJ——1024 Max Sum Plus Plus_第1张图片
没有填的说明不用算。
很显然dp[i][i]=dp[i-1][i-1]+a[i],
所以对角线上面有:
杭电OJ——1024 Max Sum Plus Plus_第2张图片
现在演示一下转移过程。如何求下图的框中的元素的值
杭电OJ——1024 Max Sum Plus Plus_第3张图片

由下面涂色的元素的最大值加上a[3]=-2求的如下图
杭电OJ——1024 Max Sum Plus Plus_第4张图片

最大的是4,所以4+(-2)=2;框中填2;
假如框中的元素是dp[i][j],画圈的元素表示的是,左边那个是dp[i][j-1],上面的几个是dp[i-1][k](i-1<=k ,这个就是上面的转移方程的表格表示法。

#include
__int64 dp[2][1000001];
__int64 a[1000001];
__int64 b[1000001];
__int64 res;
int n,m;
__int64 Max(__int64 x,__int64 y)
{
    if(x>y)return x;
    else   return y;
}
int main()
{

//    freopen("a.txt","r",stdin);
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        int t=1;
        res=0;
        int i,j,k;
        for(i=1;i<=n;i++){b[i]=0;dp[0][i]=dp[1][i]=0;scanf("%I64d",&a[i]);}
        for(i=1;i<=m;i++)
        {
            dp[t][i]=dp[1-t][i-1]+a[i];
            __int64 max=dp[1-t][i-1];
            for(j=i+1;j<=n-m+i;j++)
            {
                max=Max(max,dp[1-t][j-1]);
                dp[t][j]=Max(dp[t][j-1],max)+a[j];
            }
            t=1-t;
        }
        t=1-t;
        res=-1111111111111;
        for(j=m;j<=n;j++)if(resprintf("%I64d\n",res);
    }

    return 0;
}

你可能感兴趣的:(acm)