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
思路:在找左端点L的时候,只有以a[L-1]结尾的子序列最大和为负数的时候才是左端点开始的时候,因为无论第L个数是正是负,若以a[L-1]结尾子序列最大和为负,加上第L个数都会使以a[i]结尾的序列最大和变小 ,所以第L个数是子序列最大和的起点;
a[i]:
一,成为一个新序列的起点;dp[i]=a[i];
二,成为一个序列的终点;dp[i]=dp[i-1]+a[i];
状态方程:dp[i]=max(dp[i-1]+a[i],a[i]);
如: a[i]; 0 -1 2 4 5 0 6 -1 -1 6
dp[i]: 0 -1 2 6 11 0 6 5 4 10
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[100001];
int dp[100001];//dp[i]表示以a[i]结尾的连续子序列最大和;
int main()
{
int t,n,m=1;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
dp[0]=0;
for(int i=1;i<=n;i++)
{
dp[i]=max(a[i],dp[i-1]+a[i]);//求以a[i]结尾的子序列的的最大和;
}
int maxn=-100000,r;
for(int j=1;j<=n;j++)
{
if(dp[j]>maxn)
{
maxn=dp[j];
r=j;//找右区间;
}
}
int l=r;
for(int i=r-1;i>=1;i--)
{
if(dp[i]>=0)
{
l=i;
}
else
break;
}
printf("Case %d:\n",m++);
printf("%d %d %d\n",maxn,l,r);
if(t)
printf("\n");
}
return 0;
}