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
AC代码:
- #include<cstdio>
- #include<cmath>
- #include<cstring>
- #include<algorithm>
- using namespace std;
- int num[100010],sum[100010],start[100010],pos,ans,tot,t,n; //sum[i]存储以i结尾的最大子序列,start[i]为其对应的第一个位置
- int main()
- {
- int cnt=1;
- scanf("%d",&t);
- while(t--){
- scanf("%d",&n);
- for(int i=0;i<n;i++)
- scanf("%d",&num[i]);
- for(int i=0;i<100010;i++)
- sum[i]=-1000000000;
- sum[0]=num[0];
- start[0]=0;pos=1;tot=1;
- for(int u=1;u<n;u++){
- if(sum[u-1]+num[u]>sum[u]){sum[u]=sum[u-1]+num[u];start[u]=start[u-1];} //状态转移方程
- if(num[u]>sum[u]){sum[u]=num[u];start[u]=u;}
- }
- ans=-1000000000;
- for(int i=0;i<n;i++){
- if(sum[i]>ans){
- ans=sum[i];
- pos=start[i]+1;
- tot=i+1;
- }
- }
- printf("Case %d:\n%d %d %d\n",cnt++,ans,pos,tot);
- if(t) printf("\n");
- }
- return 0;
- }