PAT-A 真题- 1007. Maximum Subsequence Sum

发布于 / PAT-甲级 / 0 条评论

原题干:

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,接着给N个数组成的序列,要求找到这串序列的最大连续子序列和。接着输出这个和,并输出这个和的起始数字和终止数字。

如果有多个不同的答案,找到起止数字最小的一个并输出。

样例中的序列,最大连续子序列和为10,其中1+2+3+4=10,3+7=10,因为1和4比3和7小,所以选择1~4的和,并输出。

这是一道动态规划类问题,关于最大连续子序列和的问题详解见这里:https://www.mmuaa.com/post-236.html

为了解决多个答案的问题,我们选择从后向前遍历dp数组,就能找到有最小下标的结果。

dp数组最大的位置也就是终止位置。起始位置可以沿着终止位置向前找,找到最后一个非负数字,就是起始位置。

要特别注意对序列全为负数的判断。如果序列全部为负,要输出0和整个序列的起点和终点。如果第四个测试点过不去,就是这个原因。

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;
 
#define MAXN 10000
 
int main(){
    int A[MAXN], dp[MAXN];
    int cnt;
    scanf("%d", &cnt);
    for(int i = 0; i < cnt; i++){
        scanf("%d", &A[i]);
    }
    dp[0] = A[0];
    for(int i = 1; i < cnt; i++){
        dp[i] = max(A[i], dp[i-1] + A[i]);
    }
    int max = -0x3fffffff, start = 0, end = 0;
    for(int i = cnt-1; i >= 0; i--){
        if(dp[i] >= max){
            max = dp[i];
            end = i;
        }
    }
    if(max < 0) printf("0 %d %d\n", A[0], A[cnt-1]);
    else{
        for(int i = end; i >= 0; i--){
            if(dp[i] < 0) break;
            start = i;
        }
        printf("%d %d %d\n", max, A[start], A[end]);
    }
    return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题- 1007. Maximum Subsequence Sum
目前还没有评论,快来抢沙发吧~