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


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;;
	}
}

		





  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值