Max Sum |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
Total Submission(s): 1154 Accepted Submission(s): 467 |
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
|
Sample Output Case 1: Case 2:
|
来自 <http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=3§ionid=2&problemid=1>
分析:
设置三个标志变量记录最大值和起始位置,max,maxFrist,maxLast。
设置三个比较标量记录要比较的和的值,sum,sumFrist,sumLast。
思路:从头往后加,不断比较sum并记录下最大的max值,若果sum为负数,就没有往后加的意义了
此时将sum置零,sumFrist为sumLast+1( <n ),sumLast++( <n ),继续执行。
按照思路打了一段代码,中间少考虑了最大值是负数的情况,修修补补,千辛万苦终于AC了,却发现代码变得很不简洁。
#include<iostream>
usingnamespace std;
intmain()
{
intnumber,n,m,theCase = 1;
scanf("%d",&n);
while(n--)
{
intmax = -1001,maxFrist = 0,maxLast = 0;
intsum = 0,sumFrist = 1,sumLast;
scanf("%d",&m);
for(sumLast= 1; sumLast <= m; sumLast++)
{
scanf("%d",&number);
sum+= number;
//总和小于零时,没有再加下去的意义
if(sum< 0)
{
while(number < 0) //如果输入是负数,直接用最大值比较(最大值是负数的情况),直到输入为正或输入结束为止。
{
if(max< number)
{
max= number;
maxFrist= sumLast;
maxLast= sumLast;
}
if(++sumLast> m) break;
scanf("%d",&number);
}
sum = number; //while出来后,number是正数,sum从这个正数继续加下去
sumFrist= sumLast;
}
if(max>= sum) continue;
max= sum;
maxFrist= sumFrist;
maxLast= sumLast;
}
cout<< "Case " << theCase << ":" <<endl;
cout<< max << " " << maxFrist << " "<< maxLast << endl;
if(n)cout << endl;
theCase++;
}
return0;
}
于是我重整思路,尽力将代码简洁化如下:
#include<iostream>
usingnamespace std;
intmain()
{
intm,n,useCase = 1,number;
cin>> m;
while(m--)
{
intsum = 0,sumFrist = 0,sumLast;
intmax = -1001,maxLast = 1,maxFrist = 1;
cin>> n;
for(sumLast= 1; sumLast <= n; sumLast++)
{
cin>> number;
if(number < 0 && max >= number && sum ==0) continue;
sum+= number;
sumFrist++;
if(max< sum)
{
max= sum;
maxFrist= sumLast - sumFrist + 1;
maxLast= sumLast;
}
if(sum< 0)
{
sum= 0;
sumFrist= 0;
}
}
cout<< "Case " << useCase++ << ":" <<endl;
cout<< max << " " << maxFrist << " "<< maxLast << endl;
if(m)printf("\n");
}
}
当提交结果,显然也是AC,但发现时间由0ms变为了328ms!
人们总是在不满足和探索中让思想步步上升,编程也是这样,思考创造然后逐步完善,在对比前后两处代码后,我发现主要是在对于负数较多的情况下第一种效率高,第一种是不断比较max和number来考虑是否赋值
,而另一种赋值给sum再与max比较,最后再置sum=0,考虑至此,我在中间加了条语句
if(number < 0 && max >=number && sum == 0) continue;,结果就将时间降低到46ms,如下图