01-复杂度2 Maximum Subsequence Sum (25分)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sysusyf/article/details/50987619
01-复杂度2 Maximum Subsequence Sum   (25分)

Given a sequence of KK integers { N1N1N2N2, ..., NKNK }. A continuous subsequence is defined to be { NiNiNi1Ni+1, ..., NjNj } where 1ijK1ijK. 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 KK (1000010000). The second line contains KK 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 ii and jj (as shown by the sample case). If all the KK 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
主要思路:
1、在线处理去求最大子列和
2、在线处理的同时记录下当前和最大的子列的第一个和最后一个结点
3、sum<0后要记录之后可能出现和最大的子列的第一个结点
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, const char * argv[])
{
    //input
    int K;
    cin>>K;
    vector<int> vec;
    int value;
    for (int i=0; i<K; ++i)
    {
        cin>>value;
        vec.push_back(value);
    }
    
    //Process
    int first=0,last=0,sum=0,max=-1;
    int flag_max=0;//flag represent whether max has been rewrite
    int flag=0;//sum归零一次,有可能后续子数列会出现大于当前max的数列
    int maybe_first=0;//可能成为最大子列和的第一个结点
    for (int i=0; i<vec.size(); ++i)
    {
        sum+=vec[i];
        if (sum>max)//更新最大子列和
        {
            flag_max=1;
            if (flag==0)//sum更新为0后再次出现大于之前max的最大子列和,更新最大子列和的第一个结点
            {
                first=maybe_first;
                flag=1;
            }
            max=sum;
            last=i;//每次出现新的最大子列和都要更新该子列的最后一个结点
        }else if(sum<0)//sum出现小于0的情况,后续子列若出现更大的子列和,则该子列的第一个结点保存为maybe_first
        {
            maybe_first=i+1;
            sum=0;
            flag=0;
        }
    }
    
    //Output
    if (flag_max==0)
    {
        cout<<"0"<<' '<<vec[0]<<' '<<vec[vec.size()-1];
    }else
    {
        cout<<max<<' '<<vec[first]<<' '<<vec[last];
    }
    
    
    
    return 0;
}

展开阅读全文

没有更多推荐了,返回首页