zoukankan      html  css  js  c++  java
  • 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
    

     题目大意:从n个数中取m段和最大

    dp[i][j]表示从前i个数中取j段(第i个数一定取), 所以i可以单独一段,也可以和前面构成连续的一段。推出状态转移方程dp[i][j]=max(dp[i-1][j]+a[i],dp[k][j-1]+a[i]) ,k的范围为j-1到i-1

    但是这道题n和m比较大,二维的状态显然不行,所以需要降维。

    #include <bits/stdc++.h>
    using namespace std;
    int a[100005],pre[100005],dp[100005];  
    int main()
    {
        int n,m,k;
        ios::sync_with_stdio(false);
        while(cin>>m>>n)
        {
            for(int i=1;i<=n;i++) cin>>a[i];
            memset(pre,0,sizeof(pre));
            memset(dp,0,sizeof(dp));
            int maxx;
            for(int i=1;i<=m;i++)   //分成i段 
            {
                maxx=-99999999;
                for(int j=i;j<=n;j++)
                {
                    dp[j]=max(dp[j-1],pre[j-1])+a[j];    //取到第j个元素时,可以分成i段的最大值 
                    pre[j-1]=maxx;     //用前j-1个元素分成i段的最大值 
                    maxx=max(maxx,dp[j]);
                }
            }
            cout<<maxx<<endl;
        }
    } 
  • 相关阅读:
    c++命名空间重命名
    ssh保持长连接的配置方法
    macos平台上使用 sed
    c++的使用
    NAT介绍以及穿透各种类型nat的技术实现包括对称型nat
    组态图绘制软件的实现
    关于五防系统
    Linux的应用
    java常用包及其类概述
    springboot整合redis
  • 原文地址:https://www.cnblogs.com/ww123/p/10640583.html
Copyright © 2011-2022 走看看