Max Sum(杭电OJ1003)解题报告

本文探讨了最大子序列和问题的两种解决方法:一种是通过双层循环暴力搜索求解,但效率较低;另一种是利用动态规划进行优化,提高了算法效率。文中详细介绍了动态规划方法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Max Sum

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
解题思路刚开始用最笨的方法试了一下,暴力搜索,全部走一边,时间花太多
了,超时了,对此改进了搜索的方式,只要两个循环就搞定了,时间加快了,但是相
对于来说还不是最快的,还是会超时的,一个个向后面走,只要和大于Max的,就记
录的,代码如下:
Code:
  1. #include<iostream>
  2. usingnamespacestd;
  3. intmain()
  4. {
  5. intn;
  6. cin>>n;
  7. intpoint1,point2;
  8. intstep=1;
  9. while(n)
  10. {
  11. intmax=-99999;
  12. intm,data[100000];
  13. cin>>m;
  14. for(inti=1;i<=m;i++)
  15. cin>>data[i];
  16. for(i=1;i<=m;i++)
  17. {
  18. intsum=0;
  19. for(intj=i;j<m;j++)
  20. {
  21. sum+=data[j];
  22. if(sum>max)
  23. {
  24. max=sum;
  25. point1=i;
  26. point2=j;
  27. }
  28. }
  29. }
  30. if(step!=1)
  31. cout<<endl;
  32. cout<<"Case"<<step<<":"<<endl;
  33. cout<<max<<""<<point1<<""<<point2<<endl;
  34. step++;
  35. n--;
  36. }
  37. return0;
  38. }
交上去还是超时的,最近用到动态规划,对算法进行改进了,起始点还是从头开始的,
一直到后面搜索,一直和为小于零,起始点就从开始小于零的后一位开始并把sum改为
零,再搜索的过程中,一遇到大的数据就记录下来,把其计为起始点和终点的,这里
面主要考虑到,当你搜索到一个位置的,它的和不小于零的,那对于后面来说,加上
去还是会变大的,不会给变小的,所以要再搜索下去的,走一边就KO了。代码如下:
Code:
  1. #include<iostream>
  2. usingnamespacestd;
  3. #defineMin-999999
  4. intmain()
  5. {
  6. intdata[100000],start,end;
  7. intm;
  8. intstep=1;
  9. cin>>m;
  10. while(m--)
  11. {
  12. intn;
  13. cin>>n;
  14. for(inti=1;i<=n;i++)
  15. cin>>data[i];
  16. intmax=Min;
  17. intk=1;
  18. intsum=0;
  19. for(i=1;i<=n;i++)
  20. {
  21. sum=sum+data[i];
  22. if(sum>max)
  23. {
  24. max=sum;
  25. start=k;
  26. end=i;
  27. }
  28. if(sum<0)
  29. {
  30. sum=0;
  31. k=i+1;
  32. }
  33. }
  34. if(step!=1)
  35. cout<<endl;
  36. cout<<"Case"<<step<<":"<<endl;
  37. cout<<max<<""<<start<<""<<end<<endl;
  38. step++;
  39. }
  40. return0;
  41. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值