(hdu step 3.2.1)Max Sum(简单dp:求最大子序列和、起点、终点)

来源:互联网 发布:poe软件怎么用 编辑:程序博客网 时间:2024/05/16 17:10

在写题解之前给自己打一下广告哈~委屈。。抱歉了,希望大家多多支持我在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 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
 
Author
Ignatius.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;}




1 0
原创粉丝点击