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
我做这道题时试了三种做法:
前两种分别是:
把输入存进数组,再遍历,不用说,超时!
第二种,把输入存入数组,从头开始,对于sum大于0者,逐个往后加上去,对于出现sum小于0者,则放弃当前子串,sum置为0,从当前子串的下一个位置开始算sum。
问题是还是超时,因为初始化和存入数组用了太多时间了!
第三种直接逐个处理输入的数字,同步更新起始位置,终止位置以及sum和max,就AC了。可见有时候在考虑一下又能节省出许多时间!!
代码:
#include <iostream>
using namespace std;
int main()
{
int j;
int n,m;
int s=0;
int temp=0;
int start,end;
int max=-1001;
int sum=0;
int q=1;
cin>>n;
while(n--)
{
sum=0;
temp=0;
max=-1001;
s=0;
cin>>m;
while(m--)
{
cin>>j;
sum+=j;
if(sum>max)
{
max=sum;
start=s;
end=s+temp;
}
temp++;
if(sum<0)
{
sum=0;
s=s+temp;
temp=0;
}
}
if(q!=1)
cout<<endl;
cout<<"Case "<<q++<<":"<<endl;
cout<<max<<' '<<start+1<<' '<<end+1<<endl;;
}
}
版权声明:本文为ssdut_209原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。