题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1003
题目描述:
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
分析:这题跟最大连续子序列基本相同,详见:http://blog.csdn.net/qq_35323001/article/details/52230977
AC代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
int N[100005],n,num,Max,sum,l,r,term,sign,K;
int main()
{
cin>>K;
num=1;
while(K--)
{
cin>>n;
sum=0;
Max=-0xffffff;
l=1;
r=1;
term=1;
for(int i=1;i<=n;i++)
{
cin>>N[i];
sum+=N[i];
if(sum>Max)//sum值大于Max就进行处理
{
Max=sum;
l=term;
r=i;
}
if(sum<0)//如果sum<0,那么就重新赋初值0,因为一个最大和子序列不可能是从负数开始的
{
sum=0;
term=i+1;//下一个子序列是从i+1开始的,因为着了的sum值并没有把N[i]记录进去
}
}
cout<<"Case "<<num++<<":"<<endl;
cout<<Max<<" "<<l<<" "<<r<<endl;
if(K>=1)
cout<<endl;
}
return 0;
}