Max Sum Plus Plus HDU - 1024 (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 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.

题目大意:给你 一个数组 ,让你在其中选择 m 个连续子串,求这些子串的最大值。

解题思路:首先对于 dp[ i ][ j ],其中 i 表示已经选择了 i 个连续子串,j 表示前 j 个元素。那么对于数字 a[ j ] 它就有两种状态,第一种就是前面 j - 1个元素已经组成了 i - 1 个子串,则需要 a[ j ]单独组成一个子串,那么dp[ i ][ j ] = dp[ i - 1][ k ] +a[ j ],其中 dp[ i - 1][ k ]表示在j前面的数字中组成 i - 1 个子串的所有情况中的最大值,这样才能使 dp[ i ][ j ]最大。 第二种就是前面 j - 1 个元素已经组成了 i 个子串 ,那么要让a [ j ]加入进去且只有 i 个子串的话,就是 a [ j ] 加入最后一个子串(即第 i 个子串),那么 dp[ i ][ j ]= dp [ i ][ j - 1] + a[ j ]。最后转移方程为dp[ i ][ j ] = max(dp[ i - 1][ k ] +a[ j ] , dp [ i ][ j - 1] + a[ j ] )。

                 由于这个数组长度达到 1e6 显然用 n方的复杂度是完成不了的,因此要考虑滚动数组的优化。用dp [ i ]表示有 i 个子串时的状态,MAX[ i ]来表示 组成 i 个子串时的最大值。MAX数组需要在 组成子串数不变时的循环内不断更新即可。

代码: 

#include<bits/stdc++.h>
#define ll long long
#define MOD 998244353 
#define INF 0x3f3f3f3f
#define mem(a,x) memset(a,x,sizeof(a))  
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
int a[1000005];
int dp[1000005];
int MAX[1000005]; //表示前j-1个元素分成m组的最大值。
int n,m;

int main()
{
    while(~scanf("%d %d",&m,&n)){
         for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
         }
         mem(dp,0);
         mem(MAX,0);
         int maxn;
         for(int i=1;i<=m;i++){
            maxn=-INF;
            for(int j=i;j<=n;j++){
                dp[j]=max(dp[j-1]+a[j],MAX[j-1]+a[j]);
                MAX[j-1]=maxn;
                maxn=max(maxn,dp[j]);

            }
         }
         cout<<maxn<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hachuochuo_/article/details/107649231