1481:Maximum sum(2.6基本算法之动态规划)

来源:互联网 发布:用u盘制作linux启动盘 编辑:程序博客网 时间:2024/05/17 09:43

1481:Maximum sum

总时间限制: 1000ms 内存限制: 65536kB
描述
Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below:
t1 t2
d(A) = max{ ∑ai + ∑aj | 1 <= s1 <= t1 < s2 <= t2 <= n }
i=s1 j=s2

Your task is to calculate d(A).
输入
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.
输出
Print exactly one line for each test case. The line should contain the integer d(A).
样例输入
1

10
1 -1 2 2 3 -3 4 -4 5 -5
样例输出
13
提示
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.

Huge input,scanf is recommended.

#include<iostream>#include<string.h>using namespace std;//http://noi.openjudge.cn/ch0206/1481///又和上次犯一样的错误,如果只用2个dp数组存储,然后用两重循环来做会超时//应该是从前往后和从后往前分别得到dp,再分别用另一个数组存储到某位置最大值,然后再找最大值 int t,n,a[55000],s1[55000],s2[55000],res;int dp1[55000],dp2[55000];//s存储的是从前往后和从后往前到某个位置的最大子集和 void f(){    memset(dp1,0,sizeof(dp1));    memset(dp2,0,sizeof(dp2));    memset(s1,0,sizeof(s1));    memset(s2,0,sizeof(s2));    s1[0]=a[1];s2[n+1]=a[n];    for(int i=1;i<=n;i++){        dp1[i]=max(dp1[i-1]+a[i],a[i]);        s1[i]=max(s1[i-1],dp1[i]);    }    for(int i=n;i>=1;i--){        dp2[i]=max(dp2[i+1]+a[i],a[i]);        s2[i]=max(s2[i+1],dp2[i]);    }    for(int i=2;i<=n;i++){        res=max(res,s1[i-1]+s2[i]);    } }int main(){    cin>>t;    while(t--){        cin.get();        cin>>n;        res=-999999;        for(int i=1;i<=n;i++)cin>>a[i];        f();        cout<<res<<endl;    }}
原创粉丝点击