(hdu step 3.2.1)Max Sum(簡單dp:求最大子序列和、起點、終點),hdu3.2.1
在寫題解之前給自己打一下廣告哈~。。抱歉了,希望大家多多支援我在CSDN的視頻課程,地址如下:
http://edu.csdn.net/course/detail/209
題目:
| Max Sum |
| Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
| Total Submission(s): 1390 Accepted Submission(s): 542 |
| |
Problem DescriptionGiven 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.
|
InputThe 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).
|
OutputFor 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 |
AuthorIgnatius.L
|
題目分析:
簡單DP。這道題是求最大子序列的和,並且要求最大子序列的起點和終點。如果不需要求起點和終點的話。直接可以有last = max(0,last) + a[i]; ans = max(last,ans)來求解即可。但,其實就算要求起點和終點,思路還是一樣的這是只不過不能就直接max(0,last)。應該把這個邏輯展開,求產生當前最大序列和的起點和終點。
如果只求和可以參考一下:http://blog.csdn.net/hjd_love_zzt/article/details/31782777
如果這篇部落格看的不明白的話,可以先去看一下這篇:http://blog.csdn.net/hjd_love_zzt/article/details/43562931
代碼如下:
/* * a1.cpp * * Created on: 2015年2月6日 * Author: Administrator */#include <iostream>#include <cstdio>using namespace std;int main(){int t;scanf("%d",&t);int k;for(k = 1 ; k <= t ; ++k){int n;scanf("%d",&n);int start = 1;//最大子序列和的起點.預設為1int end = 1 ;//最大子序列和的終點.預設為1.int thisSum = 0;//當前子序列的和int maxSum = -100005;//最大子序列的和int index = 1;//當前子序列的起點int i;int temp;for(i = 1 ; i <= n ; ++i){scanf("%d",&temp);thisSum += temp;//當前子序列的和不斷地增加if(thisSum > maxSum){//如果當前子序列的和>最大子序列和maxSum = thisSum;//更新最大子序列和start = index;//將最大子序列的起點更新為當前子序列的起點end = i;//將最大子序列的終點更新為當前遍曆到的這個數(因為這個數產生了目前最大的子序列和)}//需要注意的是,就算thisSum並沒有比maxSum要大.這時候序列並沒有斷,要看一下後面是否會回升/** * 需要注意的是,前面不要把這兩個if語句寫成 * if(){ * }else if(){ * }的結構 * * 因為thisSum < maxSum && thisSum < 0 的情況是存在的 */if(thisSum < 0){//如果後面沒有回升,相反已經<0了thisSum = 0;//斷開原來的子序列,重新記數index = i+1;//更新當前子序列的起點}}printf("Case %d:\n",k);printf("%d %d %d\n",maxSum,start,end);if(k != t){printf("\n");}}return 0;}