• hdu1024 Max Sum Plus Plus (Dp)


    hdu1024 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 ≤ iy ≤ 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. ^_^ 
    Input
    Each test case will begin with two integers m and n, followed by n integers S 1, S2, S 3 ... S n. 
    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 recommende
     
    解题思路:
    首先定义各个数组,尽量易懂,
    a[i] 储存输入的数据
    now[j],表示以第j个元素为结尾的i个子段的最大和,必须包含a[j]。
    pre[j],表示前j个元素i个子段的最大和,不一定包含a[j]。
    dp[i][j],表示前j个元素i个子段的最大和,包含a[j]。
    原始状态转移方程:
    dp[i][j]=max(dp[i][j-1]+a[j],dp[i-1][k]+a[j])         (i-1<=k<=j-1)
    有两种情况:
    1.直接将第j个元素加在第i个子段之后。
    2.第j个元素单独作为一个子段,那么前面必须是i-1个子段。
    状态转移方程就是比较这两种情况较大值
     
    实现代码:
    #include<iostream>
     #include<algorithm>
     #include<cstdio>
     #include<cstring>
     using namespace std;
     #define M 1000002
     int a[M],now[M],pre[M];
     int main()
     {
         int m,n,i,j,Max;
         while(scanf("%d%d",&m,&n)==2)
         {
             for(i=1;i<=n;i++)  
                 scanf("%d",&a[i]);
             memset(now,0,sizeof(now));
             memset(pre,0,sizeof(pre));
             for(i=1;i<=m;i++)
             {
                 Max = -999999999;  //此处max值尽量开大,max是和,开小了就WA,
                 for(j=i;j<=n;j++)
                 {
                     now[j]=max(now[j-1]+a[j],pre[j-1]+a[j]);
                    //now[j]有两种来源,一种是直接在第i个子段之后添加a[j]
                    //一种是是a[j]单独成为1个子段
                     pre[j-1]=Max;       //更新pre使得pre是前j-1个中最大子段和
                     if(now[j]>Max)  
    Max=now[j]; } } printf("%d ",Max); } return 0; }
  • 相关阅读:
    夜游遂宁滨江路
    易中天讲座十句人生感悟(发人深省,耐人寻味)
    遥望死海
    一直被忽略的成功之道:勤快并非优点,成功需要懒惰
    给别人以宽容,给自己以信心
    合理支配“财富”:经理人运用时间的12种典型模式
    三月的清晨
    学习的三重境界(想成功的人都不可错过)
    上班
    持续开发你的事业智慧:企业家保持冲锋势头的路径
  • 原文地址:https://www.cnblogs.com/kls123/p/6804434.html
Copyright © 2020-2023  润新知