菜鸟上路,杭电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
- 菜鸟上路,杭电OJ1003 最大子串问题
- 菜鸟上路,杭电OJ1002之大数相加
- 杭电ACM1003 求最大子序列和问题
- [拓展]杭电1003(最大子数组问题)
- Max Sum(杭电OJ1003)解题报告
- 菜鸟上路 杭电OJ 1005 从 斐波那契到 快速幂
- 杭电 1231 最大连续子序列
- 杭电 1231 最大连续子序列
- 杭电ACM1003 最大子数组之和
- 杭电1231最大连续子序列
- 杭电1081--二维最大子序列
- 杭电-5586-最大子序列和
- 【杭电1231】最大连续子序列
- 杭电-1231 最大连续子序列
- 杭电1231 最大连续子序列
- 【杭电1559】最大子矩阵
- ***【杭电1559】最大子矩阵
- 杭电1081 最大子矩阵和
- Android 百度地图—反地理编码—获取当前位置附近的大厦楼宇
- Swift-属性
- linux设备驱动归纳总结:2.match.probe.remove
- 迭代和递归的区别
- c++第五次实验
- 菜鸟上路,杭电OJ1003 最大子串问题
- Eclipse如何修改工程名及包名
- css hack
- 登记销售订单api
- 五种方式解决乱码
- iOS开发学习路径的一些建议
- 过滤器-编码
- 二维数组
- Swift-方法