PAT甲级-1007-Maximum Subsequence Sum (25 分)

描述

传送门:我是传送门

Given a sequence of $K$ integers { $N_1, N_2, …, N_K$ }. A continuous subsequence is defined to be { $N_i, N_i+1, …, N_j$ } 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.

输入

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.

输出

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.

样例

输入

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

输出

1
10 1 4

思路

两个月不写代码的咸鱼不仅代码写不出来了,就连题目都开始读不明白了。。。

其实就是非常简单的DP,但是现在我竟然连DP都写错(而且还写错好几次。。。

把DP无脑扔给队友真不是好习惯。。。

一句话题意:求最大子串和,并输出它以及子串首尾的两个数字。

特殊情况:

  1. 有多个子串和相同,输出前边的。
  2. 如果全为负数,输出”0 第一个数 最后一个数”

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* ========================================================
*
* Filename: 1007.cpp
*
* Link:
*
* Created: 2019/01/11 11时19分04秒
*
* Author: duny31030 , duny31030@126.com
* Organization: QLU_浪在ACM
*
* ========================================================
*/
#include <bits/stdc++.h>
using namespace std;
#define clr(a, x) memset(a, x, sizeof(a))
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define pre(i,a,n) for(int i=n;i>=a;i--)
#define ll long long
#define ios ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int N = 100010;

int a[N];
int p[N];
int mmax = -INF;
int s1 = -1,s2 = -1;
int e = -1;

int main()
{
ios
#ifdef ONLINE_JUDGE
#else
freopen("in.txt","r",stdin);
// freopen("out.txt","w:",stdout);
#endif

int n;
cin >> n;
rep(i,1,n)
{
cin >> a[i];
}
rep(i,1,n)
{
if(a[i]+p[i-1] >= 0)
{
p[i] = a[i]+p[i-1];
if(a[i]+p[i-1] <= a[i])
{
p[i] = a[i];
s1 = i;
}
}
else
{
p[i] = a[i];
s1 = i;
}
if(p[i] > mmax)
{
mmax = p[i];
s2 = s1;
e = i;
}
}
if(mmax < 0)
cout << "0 " << a[1] << " " << a[n] << endl;
else
cout << mmax << " " << a[s2] << " " << a[e] << endl;
fclose(stdin);
// fclose(stdout);
return 0;
}