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设前i项和为sum(i);最大值比较容易,易知状态转移方程为:f(i)=max(f(i)+f(i-1),sum(i-1));比较坑的是所求最大值的起点与终点需要特别记录;还有输出最后一行没有空行;#include<stdio.h> #include<algorithm> using namespace std; struct p { long long num; int st; }sum[100005]; int main() { int n; int m; long long a[100005]; scanf("%d",&n); for (int k=0;k<n;k++) { scanf("%d",&m); for (int i=0;i<m;i++) { scanf("%I64d",&a[i]); } for (int i=0;i<n;i++) { sum[i].num=0; sum[i].st=0; } sum[0].num=a[0]; int local=0; for (int i=1;i<m;i++) { sum[i].num=max(sum[i-1].num+a[i],a[i]); if (sum[i-1].num<0) { local=i; sum[i].st=local; } else { sum[i].st=local; } } long long ans=sum[0].num; int t=0; for (int i=0;i<m;i++) { if (sum[i].num>ans) {ans=sum[i].num; t=i;} } printf("Case %d:\n",k+1); printf("%I64d %d %d\n",ans,sum[t].st+1,t+1); if (k!=n-1) printf("\n"); } }