zoukankan      html  css  js  c++  java
  • HDU1024 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(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. ^_^

    InputEach 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.
    OutputOutput 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.
    别的博客在原理上说得很清楚了,代码里的注释解释了一下是如何进行时空优化的。
    #include <bits/stdc++.h>
    #define INF 1<<30 
    using namespace std;
    int a[1000005];
    int dp[1000005]={0};//dp[i,j]表示选取a[j]分成i段的最大子段和 dp[i][j]=max(dp[i][j-1]+a[j],dp[i-1][k]+a[j])(k:i-1~j-1) 
    int m,n;
    int pre[1000005]={0};
    int main()
    {
        while(scanf("%d%d",&m,&n)!=EOF)
        {
            memset(dp,0,sizeof(dp));
            memset(pre,0,sizeof(pre));
            int i,j;
            for(i=1;i<=n;i++)
            {
                scanf("%d",&a[i]);
            } 
            int ans=0;
            for(i=1;i<=m;i++)
            {
                ans=-INF;//因为所求的最大状态一定在i=m这一轮出现,所以每轮开始把ans设为负无穷没有影响 
                for(j=i;j<=n;j++)//从i开始,要不然的话少于i个数分不成i段了 
                {
                    dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]);//在这里,一开始整个pre数组存储的本身就是i-1阶段里的各个最大值
                    pre[j-1]=ans;//当第二重循环跑起来时 ,在更新dp数组的同时也在更新pre数组,这就是这一句的含义,而在这一重循环中更新pre数组对当前是没有影响的(因为已经越过去了) 
                    ans=max(ans,dp[j]);//在开头初始化后,ans能保证一直是当前层的最大值 
                }
            }
            cout<<ans<<endl;
        }     
        return 0;
     } 
    
    
  • 相关阅读:
    使用SecureCRTP 连接生产环境的web服务器和数据库服务器
    CSS之浮动
    CSS之定位
    Session的过期时间如何计算?
    浏览器关闭后,Session会话结束了么?
    Spring事务注意点
    Lucene 的索引文件锁原理
    Mysql数据库的触发程序
    记一次jar包冲突
    关于jvm的OutOfMemory:PermGen space异常的解决
  • 原文地址:https://www.cnblogs.com/lipoicyclic/p/12324242.html
Copyright © 2011-2022 走看看