
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)(注意点见代码)
#include<stdio.h> struct Subsq
{ int sum; int l; int r; }; struct Subsq max_sum(int a[], int left, int right) // 在区间[left,right)寻找最大连续和
{
struct Subsq b, leftsq, rightsq; // 最优解要么全在左半边,要么全在右半边,要么起点在左半边、终点在右半边
int mid, i;
b.l=left; b.r=right;
if(b.r-b.l==) b.sum=a[b.l]; // 若只有一个元素,则返回它
else
{
mid=b.l+(b.r-b.l)/;
leftsq=max_sum(a,b.l,mid); rightsq=max_sum(a,mid,b.r);
int sum1=a[mid-], sum2=a[mid], ls=, rs=, l=mid-, r=mid+; // 起点在中间,分别向左、右推进
for(i=mid-;i>=b.l;i--)
{
ls+=a[i];
if(ls>=sum1)
{ sum1=ls; l=i; }
}
for(i=mid;i<b.r;i++)
{
rs+=a[i];
if(rs>sum2)
{ sum2=rs; r=i+; }
}
b.sum=sum1+sum2; b.l=l; b.r=r; // 记录起点在左半边、终点在右半边情况下的最大连续和
if(b.sum<=leftsq.sum) // If there are more than one result, output the first one.
{ b.sum=leftsq.sum; b.l=leftsq.l; b.r=leftsq.r; }
if(b.sum<rightsq.sum)
{ b.sum=rightsq.sum; b.l=rightsq.l; b.r=rightsq.r; }
}
return b;
} int main()
{
struct Subsq b;
int t, n, a[], i, j;
scanf("%d", &t);
for(j=;j<=t;j++)
{
scanf("%d", &n);
for(i=;i<n;i++)
scanf("%d", &a[i]);
b=max_sum(a,,n);
printf("Case %d:\n%d %d %d\n", j, b.sum, b.l+, b.r);
if(j<t) printf("\n");
}
return ;
}
AC
// 补充:最大连续和问题(详见紫书8.1)