• pat 1007【需要回顾】


    Maximum Subsequence Sum

    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

    NP 问题一直是我的短板,需要多加练习。
    状态转移方程: sum[i] = max (sum[i-1]+a[i], a[i])
    其中sum[i]表示的是以a[i]元素结尾的连续子序列的最大和

    View Code
     1 #include<stdio.h>
     2 int a[10001];
     3 int main()
     4 {
     5     int K;;
     6     int first,last ,i,maxA, sumA;
     7     int maxFirst, maxLast;
     8     scanf("%d", &K);
     9     
    10     i = 0;
    11     while (i < K)
    12     {
    13         scanf("%d",&a[i]);
    14         i++;
    15     }
    16     maxA = a[0]; sumA = a[0];
    17     first = last = 0;
    18     maxFirst = maxLast = 0;
    19 
    20     for(i = 1; i< K; i++){
    21 
    22         if(sumA + a[i]> a[i]){
    23 
    24             sumA = sumA + a[i];
    25             last ++;
    26         }
    27         else if(sumA + a[i] <= a[i]){
    28 
    29             first = last = i;
    30             sumA = a[i];
    31         }
    32 
    33         if(sumA > maxA){
    34 
    35             maxA = sumA;
    36             maxFirst = first;
    37             maxLast = last;
    38         }
    39     }
    40     if(maxA < 0)
    41         printf("0 %d %d",a[0], a[K-1]) ;
    42     else
    43      printf("%d %d %d", maxA, a[maxFirst], a[maxLast]) ;
    44 
    45     return 0;
    46 }
     
    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    NOI2015 寿司晚宴
    bzoj3456 城市规划
    DDP入门
    HAOI2018 染色
    曹冲养猪
    采药
    跳跳棋
    基础复习笔记-最短路

    康熙环球
  • 原文地址:https://www.cnblogs.com/graph/p/2983161.html
Copyright © 2020-2023  润新知