Time Limit: 1 secs, Memory Limit: 32 MB
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)
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
题目分析:
刚开始看到这个题目时,可能会把这个串变成前后两个串,然后比较这两个串的最大连续子段和,选出最大的。这样会把子段和重复计算很多次,因为要把这个大串的所有可能位置分开,然后求(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 }