POJ 2479 Maximum sum(动态规划、多段最大子序列求和)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wr339988/article/details/54693465

题目链接:http://poj.org/problem?id=2479

Description

Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below:

d(A)=max1s1t1<s2t2n{i=s1t1ai+j=s2t2aj}

Your task is to calculate d(A).

Input

The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, …, an. (|ai| <= 10000).There is an empty line after each case.

Output

Print exactly one line for each test case. The line should contain the integer d(A).

Sample Input

1

10
1 -1 2 2 3 -3 4 -4 5 -5

Sample Output

13

Hint

In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.

Huge input,scanf is recommended.

Source

POJ Contest,Author:Mathematica@ZSU

解题思路

题目意思很简单,就是求一段序列的两段最大子序列的和。这是对序列的一段最大子序列求和的推广,并且还能推广到n段子序列求和。核心的思想还是动态规划,定义两个函数:f(i,j)表示以第i个元素结尾的j段子序列最大和,g(i,j)表示前i个元素(不一定以i结尾)的j段子序列最大和。最后的结果就是g(n,2)了。两者的递推关系如下:

f(i,j)=max(f(i1,j)+ai,g(i1,j1)+ai)

g(i,j)=max(f(i,j),g(i1,j))

初始化的时候要注意把f和g的各个元素设为负无穷。

AC代码

#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int num=50005;
int n,t,a[num],f[num][3],g[num][3];

int main()
{
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
        }
        for(int i=0;i<n;i++){
            for(int j=1;j<3;j++){
                f[i][j]=g[i][j]=-INF;
            }
        }
        f[1][1]=g[1][1]=a[1];
        for(int i=2;i<=n;i++){
            for(int j=1;j<3;j++){
                f[i][j]=max(f[i-1][j]+a[i],g[i-1][j-1]+a[i]);
                g[i][j]=max(f[i][j],g[i-1][j]);
            }
        }
        printf("%d\n",g[n][2]);
    }
    return 0;
}

后记

这个方法同样适用于多段子序列最大和问题。

猜你喜欢

转载自blog.csdn.net/wr339988/article/details/54693465