Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10
-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4

题意:经典的求最大连续子序列和一点点的加难版。
题解:做法很多,数据结构的书介绍时间复杂度时作为例题分析过,除了O(n^2)的DP外可以用分治,以及题目要求的特殊性可以使用O(n)的算法。
 #include <stdio.h>
#include <iostream>
using namespace std; int a[];
int main()
{
int n, flag = ;
scanf("%d", &n);
for(int i = ; i < n; i++)
{
scanf("%d", a + i);
if(a[i] >= )
flag = ;
}
int ans = ;
int tl, tr, t;
int l, r, ma;
l = r = ;
tl = tr = t = ;
//t = a[0];
ma = ;
for(int i = ; i < n; i++)
{
if(t + a[i] <= )
{
if(t > ma)
{
ma = t;
l = tl;
r = tr;
}
t = ;
tl = i + ;
tr = i + ;
}
else
{
t += a[i];
tr = i;
if(t > ma)
{
ma = t;
l = tl;
r = tr;
} }
//cout << l << "~" << r << endl;
}
if(ma > )
printf("%d %d %d\n", ma, a[l], a[r]);
else if(ma== && flag) //特判 -1 0 -1 情况
printf("0 0 0\n");
else printf("0 %d %d\n", a[], a[n-]); }

 

最新文章

  1. strcpy函数在VS2015无法使用的问题
  2. (十八)WebGIS中清空功能和地图定位功能的设计以及实现
  3. IntelliJ IDEA注册码
  4. visual C++ 项目和解决方案的区别
  5. 413. Arithmetic Slices
  6. objective-c第六章课后练习5
  7. CreateProcessW记录
  8. Java JDBC批处理插入数据操作(转)
  9. C++安装JSONCPP
  10. 键盘enter事件时间页面绑定
  11. 【排序算法】直接选择排序算法 Java实现
  12. django框架(View)
  13. 诗人般的机器学习,ML工作原理大揭秘
  14. March 05th, 2018 Week 10th Monday
  15. 现代程序设计 homework-06
  16. Step by Step use OBD2 Scanner Guide
  17. 关于C# WinForm中进度条的实现方法
  18. 12.常用类简单介绍.md
  19. DOM的查找,新增,删除操作
  20. ubuntu安装vncserver实现图形化访问

热门文章

  1. 【转】Hbuilder MUI 页面刷新及页面传值问题
  2. 《剑指Offer》题三十一~题四十
  3. TensorFlow源码框架 杂记
  4. Alpha冲刺——第二天
  5. LintCode-374.螺旋矩阵
  6. OSG数学基础:坐标系统
  7. WITH REPLACE 含义
  8. centos7 nginx端口转发出现502的其中一种原因
  9. JSON字符串书写
  10. 在网页中显示器PDF文档