Max Sum(杭电OJ1003)解题报告
来源:互联网 发布:pc屏幕同步软件 编辑:程序博客网 时间:2024/06/16 08:07
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的,就记录的,代码如下:
- #include<iostream>
- using namespace std;
- int main()
- {
- int n;
- cin>>n;
- int point1,point2;
- int step=1;
- while(n)
- {
- int max=-99999;
- int m,data[100000];
- cin>>m;
- for(int i=1;i<=m;i++)
- cin>>data[i];
- for(i=1;i<=m;i++)
- {
- int sum=0;
- for(int j=i;j<m;j++)
- {
- sum+=data[j];
- if(sum>max)
- {
- max=sum;
- point1=i;
- point2=j;
- }
- }
- }
- if(step!=1)
- cout<<endl;
- cout<<"Case "<<step<<":"<<endl;
- cout<<max<<" "<<point1<<" "<<point2<<endl;
- step++;
- n--;
- }
- return 0;
- }
交上去还是超时的,最近用到动态规划,对算法进行改进了,起始点还是从头开始的,一直到后面搜索,一直和为小于零,起始点就从开始小于零的后一位开始并把sum改为零,再搜索的过程中,一遇到大的数据就记录下来,把其计为起始点和终点的,这里面主要考虑到,当你搜索到一个位置的,它的和不小于零的,那对于后面来说,加上去还是会变大的,不会给变小的,所以要再搜索下去的,走一边就KO了。代码如下:
- #include<iostream>
- using namespace std;
- #define Min -999999
- int main()
- {
- int data[100000],start,end;
- int m;
- int step=1;
- cin>>m;
- while(m--)
- {
- int n;
- cin>>n;
- for (int i=1; i<=n;i++)
- cin>>data[i];
- int max = Min;
- int k=1;
- int sum = 0;
- for (i=1; i<=n; i++)
- {
- sum = sum + data[i];
- if (sum > max)
- {
- max = sum;
- start=k;
- end=i;
- }
- if(sum<0)
- {
- sum=0;
- k=i+1;
- }
- }
- if(step!=1)
- cout<<endl;
- cout<<"Case "<<step<<":"<<endl;
- cout<<max<<" "<<start<<" "<<end<<endl;
- step++;
- }
- return 0;
- }
- Max Sum(杭电OJ1003)解题报告
- (解题报告)HDU1003---Max Sum
- [杭电]Max Sum
- 杭电 Max Sum
- hdu 1003 解题报告 ---- Max Sum
- HOJ 1003 Max Sum 解题报告
- HDU 1003 Max Sum 解题报告
- 杭电1003 Max Sum (dp)
- 杭电ACM1003 Max Sum
- 杭电 1003[Max Sum]
- 杭电1003 Max Sum
- 杭电1003 Max Sum
- 杭电 1003 Max Sum
- 杭电1003 Max Sum
- 杭电1003《Max Sum》
- 杭电1003---Max Sum
- 杭电1003 Max Sum
- 杭电1003 Max Sum
- C++程序员经常问的11个问题(转载)
- 内核栈的使用
- 随便唠叨~
- nRF24L01高速嵌入式无线数传模块SPI_RW函数的理解
- 悼念512汶川大地震遇难同胞——老人是真饿了(杭电OJ2187)解题报告
- Max Sum(杭电OJ1003)解题报告
- 精美HTML5网站合集[zt]
- Image Perimeters(POJ)解题报告
- JSP简介
- GridView样式
- Multisim交互式地搭建电路原理
- 在我的相册里
- asp系列(一):request对象的Cookies集合调试错误
- 先了解了解DirectX