poj 2479

Description


Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
poj 2479 - tuchengju - tuchengju的博客
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).There is an empty line after each case.

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

考查点:动态规划

思路:求两段的最大子段和。可以分别求0~i和i~n这两段的最大子段和,再相加起来求出最值。第一次直接调用求子段的代码O(n),导致总时间为O(n^2)超时;后来用数组leftMax[i]保存0~i最大子段和,rightMax[i]保存i~n最大子段和,在O(n)时间内求出;再用O(n)时间求最值

代码:

#include <iostream>
#include <stdlib.h>
#define inf -300005

using namespace std ;

int main()
{
    int t;
    int n;
   
    cin>>t;
   
    while(t--)
    {
        cin>>n;
        int * seq=new int[n];
        int * leftMax=new int[n];
        int * rightMax=new int[n];
        for (int i=0;i<n;i++)
             cin>>seq[i];
        int result=inf;
        int left=0;
        int right=0;
        int temp1=seq[0];
        int temp2=seq[n-1];
        leftMax[0]=seq[0];
        rightMax[n-1]=seq[n-1];
        for (int i=1;i<n;i++)
        {
            temp1=temp1+seq[i]>0?temp1+seq[i]:0;
            leftMax[i]=leftMax[i-1]>temp1?leftMax[i-1]:temp1;
           
            temp2=temp2+seq[n-i]>0?temp2+seq[n-i]:0;
            rightMax[n-1-i]=rightMax[n-i]>temp2?rightMax[n-i]:temp2;
        }
        for (int s=0;s<n-1;s++)
        {        
            left=leftMax[s];
            right=rightMax[s+1];
       //     cout<<left<<" "<<right<<endl;
            if (left+right>result)
                result=left+right;
        }
        cout<<result<<endl;
    }
    return 0;
}

超时代码:

#include <iostream>
#include <stdlib.h>
#define inf -300005

using namespace std ;

int maxSequence(int * A,int start,int end)
{
    int temp=0;
    int max=inf;
   
    if (start==end)
        return A[start];
   
    for (int i=start;i<=end;i++)
    {
        temp=temp+A[i]>0?temp+A[i]:0;
        max=temp>max?temp:max;
    }
    return max;
}

int main()
{
    int t;
    int n;
   
    cin>>t;
   
    while(t--)
    {
        cin>>n;
        int * seq=new int[n];
        for (int i=0;i<n;i++)
             cin>>seq[i];
        int result=inf;
        int left=0;
        int right=0;
        for (int s=0;s<n-1;s++)
        {        
            left=maxSequence(seq,0,s);
            right=maxSequence(seq,s+1,n-1);
            if (left+right>result)
                result=left+right;
        }
        cout<<result<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值