题干:
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
题目大意:
给出长度为n的序列,求出最大子段和,并让你输出和的值,和子段对应左右坐标的值。
如果所有数字都<0,则输出0和最左端最右端的值。
如果有多个符合条件的解,则输出坐标最小的一组。
解题报告:
区间问题转化为前缀的差。顺便维护结果。
AC代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define FF first
#define SS second
#define ll long long
#define pb push_back
#define pm make_pair
using namespace std;
typedef pair<int,int> PII;
const int MAX = 2e5 + 5;
int n,a[MAX];
int sum[MAX],pre[MAX];
int tmpl=1,ansl=1,ansr=1,ans=-1e9;
int main()
{cin>>n;for(int i = 1; i<=n; i++) cin>>a[i],sum[i] = sum[i-1] + a[i];int flag = 0;for(int i = 1; i<=n; i++) {if(a[i] >= 0) flag = 1;}if(flag == 0) {printf("0 %d %d\n",a[1],a[n]);return 0;}for(int i = 1; i<=n; i++) {pre[i] = pre[i-1];int tmp = sum[i] - sum[tmpl-1];if(tmp > ans) {ans = tmp;ansl = tmpl,ansr = i;}if(sum[i] < pre[i-1]) {tmpl = i+1;pre[i] = sum[i];}}printf("%d %d %d\n",ans,a[ansl],a[ansr]);return 0 ;
}