zoukankan      html  css  js  c++  java
  • PAT 甲级 1007 Maximum Subsequence Sum

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    const int maxn = 10050;
    struct node
    {
        int start,end;
        int sum;
        int value;
    }dp[maxn];
    
    int main() {
        //std::cout << "Hello, World!" << std::endl;
        int K;
        scanf("%d",&K);
        for (int i = 0; i < K; ++i) {
        scanf("%d",&dp[i].value);
        }
        int maxSum=dp[0].value;
        dp[0].sum=dp[0].value;
        dp[0].start=dp[0].end=0;
        for (int i = 1; i < K; ++i) {
            if(dp[i].value+dp[i-1].sum>dp[i].value){
                dp[i].sum=dp[i].value+dp[i-1].sum;
                dp[i].start=dp[i-1].start;
                dp[i].end=i;
            }else{
                dp[i].sum=dp[i].value;
                dp[i].start=dp[i].end=i;
            }
            maxSum=maxSum>dp[i].sum?maxSum:dp[i].sum;
        }
        if(maxSum<0){
            printf("0 %d %d
    ",dp[0].value,dp[K-1].value);
        }else{//注意输出下标最小的数值!!!
            printf("%d ",maxSum);
            for (int i = 0; i < K; ++i) {
                if(maxSum==dp[i].sum){
                    printf("%d %d
    ",dp[dp[i].start].value,dp[dp[i].end].value);
                    break;
                }
            }
        }
        return 0;
    }
    View Code

    涉及动态规划,没学过打扰勿喷,个人理解就是下一节点保存上一节点的求和或者最下下标

    ps.输出最小的首末数值

  • 相关阅读:
    洛谷 P1244 青蛙过河
    洛谷 P1004 方格取数
    洛谷 CF894A QAQ
    【题解】洛谷 P5506 封锁
    洛谷 P3884 [JLOI2009]二叉树问题
    Bzoj4894 天赋
    Bzoj4893 项链分赃
    Bzoj3583 杰杰的女性朋友
    POJ3233 Matrix Power Series
    UOJ#204 【APIO2016】Boat
  • 原文地址:https://www.cnblogs.com/jeseesmith/p/13885847.html
Copyright © 2011-2022 走看看