Maximum sum
Maximum sum
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
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.
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
Hint
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.
Huge input,scanf is recommended.
Huge input,scanf is recommended.
解析:
大意:求两个字段最大和
分析:O(n^3)定超时,需优化
# include<stdio.h> # include<string.h> int dp1[50002]; int dp2[50002]; int s[50002]; int sign[50002]; int max(int a,int b) { return a>b?a:b; } int main() { int nCase,nNum,i,Max; scanf("%d",&nCase); while(nCase--) { Max=-99999; scanf("%d",&nNum); dp1[0]=0; for(i=1;i<=nNum;i++) { scanf("%d",&s[i]); dp1[i]=max(s[i],dp1[i-1]+s[i]); } dp2[nNum]=s[nNum]; sign[nNum]=s[nNum]; for(i=nNum-1;i>=1;i--) { dp2[i]=max(s[i],dp2[i+1]+s[i]); sign[i]=max(dp2[i],sign[i+1]);//优化标记,记录i后的最大字段和 } for(i=1;i<nNum;i++) { /* int maxx=0; for(j=i+1;j<=nNum;j++) { if(maxx<dp2[j]) maxx=dp2[j]; }*/ if(Max<dp1[i]+sign[i+1]) Max =dp1[i]+sign[i+1]; } printf("%d\n",Max); } return 0; }
浙公网安备 33010602011771号