Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
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).
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)
Output
Print exactly one line for each test case. The line should contain the integer d(A).
Sample Input
1101 -1 2 2 3 -3 4 -4 5 -5
Sample Output
13
題目分析:
剛開始看到這個題目時,可能會把這個串變成前後兩個串,然後比較這兩個串的最大連續子段和,選出最大的。這樣會把子段和重複計算很多次,因為要把這個大串的所有可能位置分開,然後求(n-1次),所以肯定會逾時(如果大家不知道怎麼求最大連續子段和,參考http://blog.csdn.net/chinaczy/article/details/5040862)
AC的方法,可以從左至右記錄在一個數組,從右至左也記錄到一個數組
例如: 1 -1 2 2 3 -3 4 -4 5 -5
1 0 2 4 7 4 8 4 9 4 (第i個元素表示,包括位置i的最大連續子段和)
lSum=1 1 2 4 7 7 8 8 9 9(第i個元素表示,從0到i的最大連續子段和(未必包括位置i))
同理從後向前可求出rSum,然後把lSum和rSum同位置相加,找最大值。
#include<iostream>#include <iomanip>#include<stdio.h>#include<cmath>#include<iomanip>#include<list>#include <map>#include <vector>#include <string>#include <algorithm>#include <sstream>#include <stack>#include<queue>#include<string.h>using namespace std;inline long long Max(long long x1,int x2){if(x1>x2)return x1;return x2;}int main(){int geshu;//cin>>geshu;scanf("%d",&geshu);for(int xx=0;xx<geshu;xx++){int n;//cin>>n;scanf("%d",&n);vector<int> data(n);vector<long long> lSum(n);//既然對稱,兩頭取 記錄從0到i的最大值vector<long long> rSum(n);for(int i=0;i<n;i++)scanf("%d",&data[i]);lSum[0]=data[0];rSum[n-1]=data[n-1];long long max=lSum[0];long long tmpLast=lSum[0];for(int i=1;i<n;i++){tmpLast=Max(tmpLast+data[i],data[i]);if(max<tmpLast)max=tmpLast;lSum[i]=max;}tmpLast=rSum[n-1];max=tmpLast;for(int i=n-2;i>=0;i--){tmpLast=Max(tmpLast+data[i],data[i]);if(max<tmpLast)max=tmpLast;rSum[i]=max;}max=-99999;for(int i=1;i<n;i++){long long x1=lSum[i-1];long long x2=rSum[i];if(max<x1+x2)max=x1+x2;}//cout<<max<<endl;printf("%d\n",max);}//end for}