PAT甲级 1007 Maximum Subsequence Sum (25 分) 分治/DP

1007 Maximum Subsequence Sum (25 分)
Time limit: 200 ms
Memory limit: 64 MB
Source limit: 16 KB

Given a sequence of K K K integers {   N 1 ,   N 2 ,   . . . ,   N K   } \left \{ \ N_1,\ N_2,\ ...,\ N_K\ \right \} { N1, N2, ..., NK }. A continuous subsequence is defined to be {   N i ,   N i + 1 ,   . . . ,   N j   } \left \{ \ N_i,\ N_{i+1},\ ...,\ N_j\ \right \} { Ni, Ni+1, ..., Nj } where 1 ≤ i ≤ j ≤ K 1≤i≤j≤K 1ijK. 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

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K   ( ≤ 10000 ) K\ (≤10000) K (10000). The second line contains K K K numbers, separated by a space.

Output

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 i i and j j j (as shown by the sample case). If all the K K 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.

Example

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

题意:

输入 N N N个数构成的序列,求其最大子序列的和。

思路:

两种算法:分治算法、动态规划。

分治算法把序列一分为二,递归求解左半边的最大子序列的和与右半边的最大子序列的和,然后再求解跨越两个子序列的最大子序列的和。最终取三者中最大的和。

动态规划做法是遍历一遍数组,舍弃sum为负数的子序列。

参考代码:

#include 
const int MAXN = 10000;
int a[MAXN], n;
int main() {
    int ret = -1, sum = 0, pre = 0, n;
    scanf("%d", &n);
    int lo = 0, hi = n - 1;
    for (int i = 0; i < n; ++i) {
        scanf("%d", a + i);
        sum += a[i];
        if (ret < sum) {
            ret = sum;
            lo = pre;
            hi = i;
        }
        else if (sum < 0) {
            sum = 0;
            pre = i + 1;
        }
    }
    if (ret < 0) ret = 0;
    printf("%d %d %d\n", ret, a[lo], a[hi]);
    return 0;
}

你可能感兴趣的:(PAT甲级)