PAT 甲级 1007 Maximum Subsequence Sum
Given a sequence of K integers { N1, N2, …, 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.
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
结尾无空行
题意描述:
经典的最大子段和问题。本题不仅需要输出最大子段和,还需要找出最大子段和的起点和终点。
解题思路:
法①考虑dp,设状态f[i]为包含且以a[i]结尾的最大值,方程: f [ i ] = m a x ( f [ i − 1 ] , 0 ) + a [ i ] f[i] = max(f[i-1],0) + a[i] f[i]=max(f[i−1],0)+a[i]
AC代码实现:
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int N = 1e4+5;
int a[N];
int main() {
int n, x, sum, mx, l, r, L, R;
cin >> n;
sum = l = r = 0;
mx = -INF;
for(int i = 0; i < n; i++) {
cin >> a[i];
if(sum + a[i] >= a[i]) {
sum += a[i];
r = i;
}
else {
sum = a[i];
l = r = i;
}
if(sum > mx) {
L = a[l], R = a[r];
mx = sum;
}
}
if(mx >= 0) {
printf("%d %d %d", mx, L, R);
}
else {
printf("0 %d %d", a[0], a[n - 1]);
}
}
法②一个以a[i]结尾最大子段的定义: s u m [ i ] − m i n ( s u m [ k ] ) ( 1 < = k < i ) sum[i]-min(sum[k])~(1<=k<i) sum[i]−min(sum[k]) (1<=k<i) ,计算 m i n ( s u m [ k ] ) min(~sum[k]~) min( sum[k] )可以动态维护一个前缀和的最小值;
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int N = 1e4+5;
int a[N], sum[N];
int main() {
int n, x, mx, mn, res, l, L, R;
cin >> n;
mx = -INF, mn = INF;
l = 0;
for(int i = 1; i <= n; i++) {
cin >> a[i];
sum[i] = sum[i - 1] + a[i];
if(i == 1) res = sum[i];
else res = sum[i] - mn;
if(res > mx) {
L = a[l + 1], R = a[i];
mx = res;
}
if(sum[i] < mn) {
mn = sum[i];
l = i;
}
}
if(mx >= 0) {
printf("%d %d %d", mx, L, R);
}
else {
printf("0 %d %d", a[1], a[n]);
}
}