菜鸟上路,杭电OJ1003 最大子串问题

来源:互联网 发布:语义分割软件 编辑:程序博客网 时间:2024/06/14 03:09


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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 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;;}}


0 0