题目链接https://vjudge.net/problem/HDU-1003
题目如下
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<cstdio>
#include<iostream>
using namespace std;
int main()
{
int t,n,maxsum,maxleft,maxright,thissum;
int kase=0,thisleft;
cin>>t;
while(t--)
{
cin>>n;
cin>>maxsum;
thisleft=maxleft=maxright=1;
thissum=maxsum;
if(maxsum<0)
{
thissum=0;
thisleft=2;
}
for(int i=2;i<=n;i++)
{
int tem;
cin>>tem;
thissum+=tem;
if(thissum>maxsum)
{
maxsum=thissum;
maxleft=thisleft;
maxright=i;
}
if(thissum<0)
{
thissum=0;
thisleft=i+1;
}
}
cout<<"Case "<<++kase<<":"<<endl;
cout<<maxsum<<" "<<maxleft<<" "<<maxright<<endl;
if(t)printf("\n");
}
return 0;
}