POJ 2479 Maximum sum

Description

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
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
这个题的意思是把给定的N个数分成左右两个集合,求两个集合中的最大的连续和的和;
我一开始看到这个题的思咯是用一个P={1~N-2}把这N个数分成两个集合,枚举P,得到最大值,输出即可:
一交上去就超时:
超时代码:
#include<stdio.h>
int main()
{
    //freopen("in.txt","r",stdin);
    int cas,n,num[50001],i,p;
    int left,right,maxl,maxr,sum,max;
    scanf("%d",&cas);
    while(cas--)
    {
        max=0;
        scanf("%d",&n);
        for(i=0;i<n;i++)
            scanf("%d",&num[i]);
        for(p=1;p<n-1;p++)
        {
            left=right=0;
            maxl=maxr=0;
            for(i=0;i<p;i++)
            {
                if(left>=0)left+=num[i];
                else left=num[i];
                if(left>maxl)maxl=left;
            }
            for(i=p;i<n;i++)
            {
                if(right>=0)right+=num[i];
                else right=num[i];
                if(right>maxr)maxr=right;
            }
            sum=maxl+maxr;
            if(max<sum)max=sum;
        }
        printf("%d\n",max);
    }
    return 0;
}
上面的方法每一次枚举P都会敕个重算一次,这次先记录DP值然后再枚举P,结果AC了
LANGUAGE:C
CODE:
#include <stdio.h>

int main()
{
    //freopen("in.txt","r",stdin);
    long long T, n, i,j, a[50001], dp1[50001], dp2[50001], max;
    scanf("%lld", &T);
    while (T--)
    {
        scanf("%lld", &n);
        scanf("%lld", &a[0]);
        for (i=1; i<n; i++)
        {
            scanf("%lld", &a[i]);
        }
        dp1[0] = a[0],dp2[n-1] = a[n-1];
        for(i=1,j=n-2;i<n&&j>=0;i++,j--)
        {
            if (dp1[i-1] >=0) dp1[i] = dp1[i-1] + a[i];
            else dp1[i] = a[i];
            if (dp2[j+1] > 0) dp2[j] = dp2[j+1] + a[j];
            else dp2[j] = a[j];
        }
        for (i=1,j=n-2; i<n&&j>=0; i++,j--)
        {
            if (dp1[i] < dp1[i-1]) dp1[i] = dp1[i-1];
            if (dp2[j] < dp2[j+1]) dp2[j] = dp2[j+1];
        }
        for (i=1,max = dp1[0] + dp2[1]; i<n-1; i++)
        {
            if (dp1[i] + dp2[i+1] > max) max = dp1[i] + dp2[i+1];
        }
        printf("%lld\n", max);
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值