1007 Maximum Subsequence Sum

题目:1007 Maximum Subsequence Sum

Given a sequence of K integers { N1N2, ..., NK }. A continuous subsequence is defined to be { NiNi+1, ..., Nj } where 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 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 Knumbers 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

 

思路:

1、动态规划状态

dp[i].value 存放以a[i]结尾的连续序列的最大和  

dp[i].start存放以a[i]结尾的最大连续序列的第一个数的下标 

 

2、低级错误:输出字符串得要用“”双引号

cout<<'0 ' -> cout<<"0 "

 

代码:

 

#include<stdio.h>
#include<iostream>
using namespace std;
struct DP{
    int start, value;   
}dp[10005]; // dp[i].value 表示以下标为i的数组元素为结尾的子串的最大和
int main(){
    int k,index=0;
    int a[10005];
    cin>>k;
    for(int i=0; i<k; i++){
        cin>>a[i];
    }
    dp[0].start = 0;
    dp[0].value = a[0];
    for(int i=1; i<k; i++){
        if(dp[i-1].value + a[i] > a[i]){
            dp[i].value = dp[i-1].value + a[i];
            dp[i].start = dp[i-1].start;
        }else{
            dp[i].value = a[i];
            dp[i].start = i;
        }
    }
    
    for(int i=1; i<k; i++){
        if(dp[i].value > dp[index].value){
            index = i;
        }
    }
    
    if(dp[index].value < 0){
        cout<<"0 "<<a[0]<<' '<<a[k-1];
    }else{
        cout<<dp[index].value<<' '<<a[dp[index].start]<<' '<<a[index];
    }
    return 0;
}

 

posted @ 2022-11-12 16:40  Yohoc  阅读(15)  评论(0编辑  收藏  举报