7A - Max Sum
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
// WA*9,Time Limit Exceeded*2
代码省略
// 当需要函数返回多个值时,可使用结构类型
// 分治法(详见紫书8.1.3)(注意点见代码)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 3 struct Subsq 4 { int sum; int l; int r; }; 5 6 struct Subsq max_sum(int a[], int left, int right) // 在区间[left,right)寻找最大连续和 7 { 8 struct Subsq b, leftsq, rightsq; // 最优解要么全在左半边,要么全在右半边,要么起点在左半边、终点在右半边 9 int mid, i; 10 b.l=left; b.r=right; 11 if(b.r-b.l==1) b.sum=a[b.l]; // 若只有一个元素,则返回它 12 else 13 { 14 mid=b.l+(b.r-b.l)/2; 15 leftsq=max_sum(a,b.l,mid); rightsq=max_sum(a,mid,b.r); 16 int sum1=a[mid-1], sum2=a[mid], ls=0, rs=0, l=mid-1, r=mid+1; // 起点在中间,分别向左、右推进 17 for(i=mid-1;i>=b.l;i--) 18 { 19 ls+=a[i]; 20 if(ls>=sum1) 21 { sum1=ls; l=i; } 22 } 23 for(i=mid;i<b.r;i++) 24 { 25 rs+=a[i]; 26 if(rs>sum2) 27 { sum2=rs; r=i+1; } 28 } 29 b.sum=sum1+sum2; b.l=l; b.r=r; // 记录起点在左半边、终点在右半边情况下的最大连续和 30 if(b.sum<=leftsq.sum) // If there are more than one result, output the first one. 31 { b.sum=leftsq.sum; b.l=leftsq.l; b.r=leftsq.r; } 32 if(b.sum<rightsq.sum) 33 { b.sum=rightsq.sum; b.l=rightsq.l; b.r=rightsq.r; } 34 } 35 return b; 36 } 37 38 int main() 39 { 40 struct Subsq b; 41 int t, n, a[100000], i, j; 42 scanf("%d", &t); 43 for(j=1;j<=t;j++) 44 { 45 scanf("%d", &n); 46 for(i=0;i<n;i++) 47 scanf("%d", &a[i]); 48 b=max_sum(a,0,n); 49 printf("Case %d:\n%d %d %d\n", j, b.sum, b.l+1, b.r); 50 if(j<t) printf("\n"); 51 } 52 return 0; 53 }
// 补充:最大连续和问题(详见紫书8.1)