1007 Maximum Subsequence Sum (25 分)
Given a sequence of KKK integers { N1N_1N1, N2N_2N2, ..., NKN_KNK }. A continuous subsequence is defined to be { NiN_iNi, Ni+1N_{i+1}Ni+1, ..., NjN_jNj } where 1≤i≤j≤K1 \le i \le j \le K1≤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 KKK (≤10000\le 10000≤10000). The second line contains KKK 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 iii and jjj (as shown by the sample case). If all the KKK 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,接下来有n个整数,问这些数字的最大连续子段和为多少,输出三个数字分别为最大子段和、该最大子段第一个数字、最后一个数字。存在多个最大子段和则输出靠前的子段,如果序列的每个数字全为负数则输出的最大子段和为0,并且输出该序列的第一个数字以及最后一个数字。
思路:
- 这种题有两种做法,一个是在线,一个是离线,关于离线的做法是要写出状态转移方程,然后利用前缀和。这里采取在线的做法,策略如下:枚举每个位置的值,如果该数字加到我目前的和(sum)中,使得sum大于0的话,我就接着考虑下一个,否则如果小于0了,那么子段和就从下个位置开始考虑。每次个位置操作完毕后都要判断是否能够更新全局的max。
- 坑点:
1,当有个0,其他都为负数要输出0 0 0
2,输出的是头和尾的下标的值而不是下下标
Code:
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = (int)1e4+5;
const int inf = (1 << 31);
int val[maxn], n;
int DP (int& l, int& r) {
int nl, nr, tmp = 0;
int mmax = 0;
bool flag = false;
nl = l = 0;
nr = r = n - 1;
for (int i = 0; i < n; i++) {
tmp += val[i];
if (tmp >= 0) {
nr = i;
if (!flag) {
l = i;
r = i;
flag = true;
}
} else {
tmp = 0;
nl = i + 1;
nr = i + 1;
}
if (tmp > mmax) {
mmax = tmp;
l = nl;
r = nr;
}
}
return mmax;
}
int main() {
int l, r;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> val[i];
}
cout << DP(l, r);
cout << " " << val[l] << " " << val[r] << endl;
return 0;
}