码迷,mamicode.com
首页 > 其他好文 > 详细

PAT Maximum Subsequence Sum[最大子序列和,简单dp]

时间:2018-07-19 19:15:23      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:cst   include   ecif   数字   dice   cin   顺序   忘记   ret   

1007 Maximum Subsequence Sum (25)(25 分)

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 <= 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


#include <iostream>
#include <cstring>
#include <cstdio>
#include<map>
#include<stack>
using namespace std;
int sz[10001];
int main()
{

    //freopen("1.txt","r",stdin);
    //就是寻找最大和序列。我之前见过这种题,不过现在忘记了。
    //第一次提交12分。。。到底是哪里错了?
    //没有最小值的没有考虑到。。
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>sz[i];
    }
    int maxs=-1,thiss=0;
    int f=0,e=n-1,temp=0;
    for(int i=0;i<n;i++){
        thiss+=sz[i];
        if(thiss>maxs){
            maxs=thiss;
            e=i;
            f=temp;
        }else if(thiss<0){
            thiss=0;
            temp=i+1;
        }//这怎么标记开始和结束啊?。。。。
        //cout<<thiss<<" "<<sz[i]<<" "<<f<<" "<<e<<‘\n‘;
        }
    if(maxs<0)//第二次提交加上这个之后,得分还是12;使用了flag判断之后依旧是12分。。
        maxs=0;
    cout<<maxs<<" "<<sz[f]<<" "<<sz[e];

    return 0;
}

//emmm,这个整了有2h.第一次提交12分,主要是不太会标记开始,结束很好标记。后来提交22分,还差3分。发现主要是对数据

2

0 -1 这样的,因为我的maxs初始化为0,那么就无法进行更新。所以初始化为了-1。

//最大子序列和问题,O(n)内的问题就可以解决,顺序相加,每次都比较是否比之前的最大和大;如果出现了负值和,那肯定就不能有贡献。初始化为0.此时也标记一个新的开始,如果本次开始和序列值出现了最大,那么就会更新开始位置序号。懂了。

//还要注意读题,最大序列和为负值时要输出0和n-1位置的数字,这是题目给的。

 

PAT Maximum Subsequence Sum[最大子序列和,简单dp]

标签:cst   include   ecif   数字   dice   cin   顺序   忘记   ret   

原文地址:https://www.cnblogs.com/BlueBlueSea/p/9337573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!