美文网首页
PTA1007 最大子段和

PTA1007 最大子段和

作者: ZakWind | 来源:发表于2019-02-17 19:46 被阅读0次

    一、题目

    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\leq i\leq j\leq 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 integerK(\leq10000). 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
    

    二、思路

    若记b[j]=\max_{1\leq i\leq j}\{\sum_{k=i}^ja[k] \} ,1\leq j\leq n,则所求的最大子段和为\max_{1\leq j\leq n}b[j]
    b[j]的定义易知,当b[j-1]>0b[j]=b[j-1]+a[j],否则b[j]=a[j]。由此可得计算b[j]的动态规划递归式b[j]=max\{b[j-1]+a[j],a[j]\}, 1\leq j\leq n据此,可设计出求最大子段和的动态规划算法。

    三、代码

    #include <iostream>
    
    using namespace std;
    
    int main() {
        int k = 0;
        cin >> k;
        int *n = new int[k];
        int b = 0, sum = 0;
        int l = 0, l1 = 0, r = 0, r1 = 0;
        for (int i = 0; i < k; ++i) {
            cin >> n[i];
            if (b > 0) {
                b += n[i];
                r = i;
            } else {
                b = n[i];
                r = i;
                l = i;
            }
            if (b > sum) {
                sum = b;
                l1 = l;
                r1 = r;
            } else if (b == 0 && sum == 0) {
                l1 = l;
                r1 = r;
            }
        }
        if (l1 == 0 && r1 == 0 && b < 0)
            cout << sum << " " << n[0] << " " << n[k - 1];
        else
            cout << sum << " " << n[l1] << " " << n[r1];
    }
    

    四、注意事项

    坑点是:当全为负数时,输出0 首 尾;当有0,其余为负时,应输出0 0 0。

    相关文章

      网友评论

          本文标题:PTA1007 最大子段和

          本文链接:https://www.haomeiwen.com/subject/eaqneqtx.html