Max Sum

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

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
 
问题的想法是《编程之美》上的,修改了一下提交就ok了。。
思路:
   考虑数组的第一个元素a[0],以及最大的一段数组(a[i].....a[j])跟a[0]之间的关系,有一下几种情况:
     1. 当0=i=j时,元素a[0]本身构成和最大的一段。
     2.当0=i<j时,和最大的一段以a[0]开始。
     3.当0<i时,元素a[0]跟和最大的一段没有关系。
假设已经知道(a[1]....a[n-1])中的最大的一段数组之和为All[1],并且已经知道了(a[1]......a[n-1])中包含a[1]的和最大的一段数组为start[1]。
那么有以上情况可以得出(a[0].....a[n-1])中问题的解All[0]是三种情况的最大值max(a[0],a[0]+start[1],All[1]).
so问题符合无后效性,用动态规划方法可解决。
   
 #include<iostream>
using namespace std;
int main()
{
int t,len,m=,h,n,w,l,r,p,e,i;
cin>>t;h=t;
while(t--)
{
m++;
l=r=p=e=;
cin>>len;
int a[len];
for(i=;i<len;i++)
cin>>a[i];
n=a[],w=a[];l=;p=;
for(i=;i<len;i++)
{
if(a[i]>n+a[i]){
n=a[i];
l=i;
r=i;
}
else {
n=n+a[i];
r=i;
}
if(n>w){
w=n;
e=r;
p=l;
}
}
cout<<"Case "<<m<<":"<<endl<<w<<" "<<p+<<" "<<e+<<endl;
if(m!=h)cout<<endl;
}
return ;
}

最新文章

  1. 解决mint17-linux里chrome一搞就弹出“登陆密钥环”的框框
  2. Java中Websocket使用实例解读
  3. VS删除未使用的命名空间
  4. 不用库(框架),自己写ajax
  5. 导入libxml.dylib用Google的GDataXML解析XML数据
  6. 修改apache的默认www目录
  7. ios开发常用RGB色值
  8. AES在线加密解密-附AES128,192,256,CBC,CFB,ECB,OFB,PCBC各种加密解密源码
  9. 关于Phabricator Arcanist以及提交项目代码
  10. Javascript学习二---DOM元素操作
  11. python: 基本知识记录
  12. poj3061 Subsequence(尺取法)
  13. 六、编写第一个应用【外部nodejs调用】
  14. Http协议响应状态类别及说明
  15. python学习笔记--装饰器
  16. awk去重以某列重复的行
  17. Jquery~跨域异步上传文件
  18. c++ 常见网络协议头
  19. DNS隧道通信的检测
  20. hive引入jar包--HIVE.AUX.JARS.PATH和hive.aux.jars.path

热门文章

  1. HDOJ/HDU 1984 Mispelling4(删除第n个字符~)
  2. poj 3304 Segments(计算几何基础)
  3. HDU 1078 FatMouse and Cheese (记忆化搜索+dp)
  4. hadoop家族之mahout安装
  5. MySQL添加外键时报错 ERROR 1215 (HY000): Cannot add foreign key constraint
  6. 无法定位序数XX于动态链接库XX.dll的解决的方法
  7. Android开发_控制硬加速hardwareAccelerated
  8. EditText操作收集
  9. 从Swap函数谈加法溢出问题
  10. 一句代码,更加优雅的调用KVO和通知