POJ 2479 Maximum sum

来源:互联网 发布:java线程同优先级调度 编辑:程序博客网 时间:2024/04/30 12:02

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

1101 -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);    }}


	
				
		
原创粉丝点击