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
题意:求最大的子段和,和它的起始位置和终止位置。
解题思路:
在输入的时候,就可以开始求最大子段和了。当前子段和的值为负值时,就没必要再往下进行,而应将下一位数作为子段的第一位。也就是说,当处理第i个数时,如果以第i-1个数为结尾的子段的和为正数,则不必将第i个数作为新子段的首位进行枚举,因为新子段加上前面子段和所得的正数,一定能得到更大的子段和。然后在标记下位置就好了....
代码如下:
1 #include<stdio.h> 2 int a[100005]; 3 int main() 4 { 5 int T; 6 int N=0; 7 scanf("%d",&T); 8 while(T--) 9 { 10 N++; 11 int n,max=-1010,l=0,r=0,sum=0,temp=1; 12 scanf("%d",&n); 13 for(int i=1; i<=n; i++) 14 { 15 scanf("%d",&a[i]); 16 sum+=a[i]; 17 if(sum>max) 18 { 19 max=sum; 20 l=temp; 21 r=i; 22 } 23 if(sum<0) 24 { 25 sum=0; 26 temp=i+1; 27 } 28 } 29 printf("Case %d: %d %d %d ",N,max,l,r); 30 if(T) 31 printf(" "); 32 } 33 }