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
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N=100005;
int a[N];
int f[N][2];
int main(){
int t,n;
scanf("%d",&t);
int c=0;
while(t--){
printf("Case %d:\n",++c);
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
int maxs=a[0];
f[0][0]=a[0];
f[0][1]=0;
int p=0;
for(int i=1;i<n;i++){
f[i][0]=max(f[i-1][0]+a[i],a[i]);
if(f[i][0]>maxs){
maxs=f[i][0];
p=i;
}
if(maxs>0&&f[i-1][0]>=0)//!
f[i][1]=f[i-1][1];
else f[i][1]=i;
}
printf("%d %d %d\n",maxs,f[p][1]+1,p+1);//!
if(t>0) printf("\n");
}
}
题意:找出一段序列中最大的连续子序列的和,及该子序列的始末位置;
用动态规划来进行考虑,不断统计前面的和,当前面的和小于当前值时,重新以当前值为起点继续统计;统计前对如果前面和是最大则进行保存,并记录末位置;
用一个二维数组,一维用来动态规划i位置的最大和,一维用来规划i位置最大和的起始位置;
规划最大和的起始位置:当最大值大于0并且前一个位置的最大和大于0时,继续寻找前面的位置;否则就是当前位置(考虑的情况和规划最大和是同情况);
最后输出时格式略坑,同时要记住你规划的位置都是下标,所以要+1;