HDU1003

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
    求最大子序列的和,及其左右开始下标。
   甚是惭愧,现在是10月份,此题我在3月份已经在HDU上交过并AC了,但是没写题解,导致现在题出来又不会,现在必须补上。
   此前我想的是,遇到a[i]<0时,重新更新sum值,但是后来一想不对,比如这个 :  2  -1   100  更新sum的话,最大只能加到100而不是101.
   初始用dp保存输入的每个数字,而后的过程中,dp[i]为以 i 位置为结尾的最大值。如果走的过程中,dp[i-1]<0了,即累加出现<0的情况,那么就没必要再加了,因为再加就会减小。所以要从dp[i]重新累加,记录到此时的左端点  k=i;    每次for更新一次最大值(dp[i]>max),l=k,r=i;
    

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e5+;
int dp[maxn]; //maxx=max{dp[i-1]+a[i],a[i]}
int main()
{
int t;
cin>>t;
int mid=t;
int ac=;
while(t--)
{
int n;
cin>>n;
for(int i=;i<=n;i++)
cin>>dp[i];
int maxx=dp[];
int l=,r=;
int k=;
for(int i=;i<=n;i++)
{
// cout<<dp[i-1]<<endl;
if(dp[i-]>=)
{
dp[i]+=dp[i-];
}
else
{
k=i;
}
if(dp[i]>maxx)
{
maxx=dp[i];
l=k;
r=i;
}
}
printf("Case %d:\n",ac);
printf("%d %d %d\n",maxx,l,r);
if(ac!=mid)
cout<<endl;
ac++;
}
return ;
}

    注意输出,最后一句。每个样例之间输出一个空行,但是注意结尾不能有空行!

最新文章

  1. 创建maven工程时总是带有后缀名Maven Webapp解决办法
  2. 8款超实用JavaScript框架
  3. Mysql学习笔记(四)字符串函数
  4. C++中为什么构造函数不能是虚函数,析构函数是虚函数
  5. java GUI之基本图形
  6. Struts2的创建Web项目入门
  7. Andoird开发手机壁纸
  8. php 变量原理讲解
  9. ml-agent:Win10下环境安装
  10. cocos2d-x 游戏开发之有限状态机(FSM) (四)
  11. day-11函数的形参与实参
  12. idea导入svn项目
  13. DataStructs.h
  14. asp.net 连接SQL Server 数据库并进行相关操作
  15. Linux中的Diff和Patch
  16. 《剑指offer》第五十八题(左旋转字符串)
  17. Linux系统Web网站目录和文件安全权限设置
  18. ios开发之--NSString的操作
  19. 2018No-java面试知识
  20. [hadoop]mapreduce原理简述

热门文章

  1. Flume 1.9.0 的安装(比较简单, 操作也不像老版本那么繁琐了)
  2. LeetCode1029 两地调度(贪心+java自定义排序回顾)
  3. P1052 卖个萌
  4. nodejs学习笔记(一):centos7安装node环境
  5. js加密(十四)mail.yw.gov.cn/ RSA
  6. 六十五、SAP中通过BREAK-POINT下断点,进行调试
  7. Centos7安装rabbitMQ3.6.0
  8. 干货分享|留学Essay怎么写?
  9. Hive 数据类型 + Hive sql
  10. HDU - 4112 Break the Chocolate(规律)