Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 291913 Accepted Submission(s): 69228
Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4
Case 2:
7 1 6
用dp[i]表示以a[i]为end position的连续子序列的和的最大值。即dp[i]=max(a[i],dp[i-1]+a[i])。求出最大值Max后终点很容易得出,就是相应的dp[i]的下标。当最大值是负数时,起点和终点相等。当最大值非负时,起点为终点前连续的最后一次出现非负dp[i]的下标。
AC代码:
1 #include<iostream> 2 #include<cstring> 3 #include<algorithm> 4 #include<iomanip> 5 #include<cmath> 6 using namespace std; 7 int main() 8 { 9 int T,dp[100001],a[100001],i,num,j=1; 10 cin>>T; 11 while(T--) 12 { 13 cin>>num; 14 memset(dp,-1,sizeof(dp)); 15 memset(a,-1,sizeof(a)); 16 for(i=1;i<=num;i++) 17 cin>>a[i]; 18 int i0=1,in=1,Max=a[1]; 19 for(i=1;i<=num;i++) 20 { 21 dp[i]=max(a[i],dp[i-1]+a[i]); 22 if(dp[i]>Max) 23 { 24 Max=dp[i]; 25 i0=in=i; 26 } 27 } 28 while(dp[i0]>=0) i0--; 29 if(i0<in) i0++; 30 cout<<"Case "<<j++<<':'<<endl; 31 cout<<Max<<' '<<i0<<' '<<in<<endl; 32 if(T>0) cout<<endl;//注意格式 33 } 34 } 35