[sicily online]1091. Maximum Sum

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

1

10
1 -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
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值