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
求最大子段和,基础题!
1 #include <stdio.h> 2 int main() 3 { 4 int t; 5 int n; 6 int a[100001]; 7 scanf("%d", &t); 8 for(int i=1; i<=t; i++){ 9 scanf("%d",&n); 10 for(int j=1; j<=n; j++){ 11 scanf("%d",&a[j]); 12 } 13 int p1,p2; 14 p1=p2=1; 15 int pos=1; 16 int temp=a[1]; 17 int res=a[1]; 18 for(int j=2; j<=n; j++){ 19 //如果之前是负的话,就重新开始存 20 //-1 3 -1 2 21 //第一次是-1的时候就重新存 22 //第二次则不需要,因为之前的和为正数 23 if(a[j]+temp<a[j]){ 24 temp=a[j]; 25 pos=j; 26 }else{ 27 temp+=a[j]; 28 } 29 //每次发现最大的时候则存放起来 30 if(temp>=res){ 31 res=temp; 32 p1=pos; 33 p2=j; 34 } 35 } 36 if(i!=1)printf(" "); 37 printf("Case %d: ", i); 38 printf("%d %d %d ", res, p1, p2); 39 } 40 return 0; 41 }