您的位置:首页 > 其它

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

2015-02-06 12:58 411 查看
在写题解之前给自己打一下广告哈~

。。抱歉了,希望大家多多支持我在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
 
[align=left]Problem Description[/align]Given a sequence a[1],a[2],a[3]......a
, 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.
 
[align=left]Input[/align]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).
 
[align=left]Output[/align]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.
 
[align=left]Sample Input[/align]
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
 
[align=left]Sample Output[/align]
Case 1:
14 1 4

Case 2:
7 1 6
 
[align=left]Author[/align]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;//最大子序列和的起点.默认为1
int 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: