POJ2479 Maximum sum

来源:互联网 发布:silverlight mac 卸载 编辑:程序博客网 时间:2024/06/05 08:40

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

Hint

In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer. 

Huge input,scanf is recommended.

题意是给出一个序列,求出这个序列中两个不相交子串的和最大。

这是一道与POJ2593相似的DP题,但这一道的数据感觉很水。

做法是dp[i]代表1到i的子串最大和。然后逆向求最大和,答案便是max(ans,dp[i-1]+Max)

就是相当于在序列中画一条分界线,左边的最大和和右边的最大和相加最大

代码如下

#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>using namespace std;#define N 50010 int a[N],dp[N];int main(){int i,j,n,m,T;scanf("%d",&T);while(T--){int cnt=0;scanf("%d",&n);for(i=1;i<=n;i++){ scanf("%d",&a[i]);if(a[i]<0) cnt++;}if(cnt==n){              sort(a+1,a+1+n);              printf("%d\n",a[n]+a[n-1]);              continue;}dp[0]=a[1];int Max=-100001,sum=0;for(i=1;i<=n;i++){sum+=a[i];dp[i]=max(sum,dp[i-1]);if(sum>Max){dp[i]=sum;Max=sum;} if(sum<=0){sum=0;dp[i]=dp[i-1];}}//for(i=1;i<=n;i++) cout<<dp[i];int ans=-10000;Max=-10000;sum=0;dp[0]=0;   for(i=n;i>=2;i--)   {     sum+=a[i];     if(sum>Max)     {     Max=sum;     ans=max(ans,dp[i-1]+Max);  }  if(sum<=0) sum=0;   }   printf("%d\n",ans);}return 0;}


1 0
原创粉丝点击