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