Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below: d(A)=max(∑t1i=s1ai+∑t2j=s2aj|1<=s1<=t1<s2<=t2<=n) d ( A ) = max ( ∑ i = s 1 t 1 a i + ∑ j = s 2 t 2 a j | 1 <= s 1 <= t 1 < s 2 <= t 2 <= n ) 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.
POJ Contest,Author:Mathematica@ZSU
给定一组N个整数:A ={A1,A2,…,An},我们定义一个函数D(A)如下: d(A)=max(∑t1i=s1ai+∑t2j=s2aj|1<=s1<=t1<s2<=t2<=n) d ( A ) = max ( ∑ i = s 1 t 1 a i + ∑ j = s 2 t 2 a j | 1 <= s 1 <= t 1 < s 2 <= t 2 <= n ) 你的任务是计算D(A)。
输入包括T(T<=30)的测试数据。 测试数据的数目(T),在输入的第一行。每个测试用例包含两行。 第一行是整数n(2<= N <=50000)。第二行包含n个整数: A1,A2,...,An。(|Ai|<=10000) A 1 , A 2 , . . . , A n 。 ( | A i | <= 10000 ) 。每个样例例后有一个空行。
每个测试用例只有一行,该行应包含整数D(A)。
在示例中,我们选择{2,2,3,-3,4}和{5},那么我们就可以得到答案。 在有巨大的输入数据时,scanf是最高效的。
POJ 竞赛,作者:Mathematica@ZSU
这是一道比较经典的动态规划题。这道题的难点主要是在怎样将问题分解。我们先从一个点开始,假定这个点的左边有一个最大子段,右边也有一个最大子段。那答案就是每个点左右最大子段的和的最大值。那怎么左右最大字段和呢?我们可以计算左边和右边到i-1,i+1点的最大和,再求i点的最大和,递推公式为: 第一步: leftsum[i]=max(a[i],a[i]+leftsum[i−1]) l e f t s u m [ i ] = max ( a [ i ] , a [ i ] + l e f t s u m [ i − 1 ] ) rightsum[i]=max(a[i],a[i]+rightsum[i+1]) r i g h t s u m [ i ] = max ( a [ i ] , a [ i ] + r i g h t s u m [ i + 1 ] ) 第二步: leftsum[i]=max(leftsum[i],leftsum[i−1]) l e f t s u m [ i ] = max ( l e f t s u m [ i ] , l e f t s u m [ i − 1 ] ) rightsum[i]=max(rightsum[i],rightsum[i+1]) r i g h t s u m [ i ] = max ( r i g h t s u m [ i ] , r i g h t s u m [ i + 1 ] ) 第三步: d(A)=max(leftsum[i]+rightsum[i+1]) d ( A ) = max ( l e f t s u m [ i ] + r i g h t s u m [ i + 1 ] ) 最后输出d(A)即可。