博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HDU 1003:Max Sum
阅读量:7225 次
发布时间:2019-06-29

本文共 2112 字,大约阅读时间需要 7 分钟。

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 174588    Accepted Submission(s): 40639


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

题意:给定一个序列,求其子序列的最大和,还有最大和的子序列的起始位置和结束位置。

求和与end都没什么好说的。求start是亮点,一开始判断了很久,后来还是那个想法,对于序列或是字符串正着想想不出来就逆过来想,从左到右end容易求,那从右至左的话start就容易求了。

代码:

#include 
#include
#include
#include
#include
#pragma warning(disable:4996) using namespace std;int value[100005];int dp[100005];int main(){ //freopen("input.txt","r",stdin); //freopen("out.txt","w",stdout); int Test,num,i,j,ans,start,end; value[0]=0; cin>>Test; for(j=1;j<=Test;j++) { ans = -1005; memset(dp,0,sizeof(dp)); cin>>num; for(i=1;i<=num;i++) { cin>>value[i]; dp[i]=max(dp[i-1]+value[i],value[i]); if(dp[i]>ans) { ans=dp[i]; end=i; } } ans=-1005; memset(dp,0,sizeof(dp)); for(i=num;i>=1;i--) { dp[i]=max(dp[i+1]+value[i],value[i]); if(dp[i]>=ans) { ans=dp[i]; start=i; } } cout<<"Case "<
<<":"<
后来看discuss里其他人的思路,觉得从end开始往回倒,对每一个值都加起来,什么时候等于求出来的最大和了,什么时候就是start了,觉得这样做也很好。

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/lightspeedsmallson/p/4785842.html

你可能感兴趣的文章
定时执行程序-Quartz简单实例
查看>>
【CF 应用开发大赛】MyfCMS系统
查看>>
windows下kangle虚拟主机-架设java空间的教程及心得
查看>>
Discuz! X2.5:文件目录结构
查看>>
我的友情链接
查看>>
TCP/IP协议及首部初了解
查看>>
防火墙iptables
查看>>
CUDA搭建
查看>>
memcached与PostgreSQL缓存命中机制
查看>>
百度地图路线检索(3)
查看>>
linux netstat 命令详解
查看>>
对前几篇blog的环境等的补充说明
查看>>
Curl命令使用解析大全
查看>>
MySQL日期函数
查看>>
【00】Effective Java
查看>>
.NET重构—单元测试重构
查看>>
SMB简介sabma服务(一)
查看>>
ANT简明教程
查看>>
Eclipse Luna WTP 与 Tomcat 8 的整合存在一个很头疼的 Bug
查看>>
小数在计算机里面的存放
查看>>