甲级-1007 Maximum Subsequence Sum (25 分)

题目:

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

解题思路:

思路参考了先前刷过的另外一道题,动态规划——买卖股票的最佳时机
这里将输入序列的{ N1,N2,...,NK }转化为了序列A{ 0,N1,N1+N2,...,N1+N2+...+NK }的形式,只需算出最大的A[m]-A[j] (0≤j 注意点——需要考虑输入序列全为负数或全为0的特殊情况。

代码:

编译器:C++(g++)

#include 
#include 
#include 
using namespace std;

pair findSubseq(const vector &srce)
{
    //数组全部为0的特殊情况
    for(int i=0,zero=-1;i0)
        {
            break;
        }
        if(i==srce.size()-1)
        {
            return make_pair(zero,zero+1);
        }
    }
    //转换为tmp{0, srce[0], srce[0]+srce[1],..., srce[0]+...+srce[n-1]}的形式
    //若tmp[m]-tmp[j]为最大值,则索引[j,m)为最大子序列
    vector tmp(1,0);
    tmp.push_back(srce[0]);
    for(int i=1,n=srce[0];itmp[tmpMax])
        {
            tmpMax=i;
        }
        if(tmp[i]value)
            {
                maxIndex=tmpMax;
                minIndex=tmpMin;
                value=tmp[tmpMax]-tmp[tmpMin];
            }
            tmpMax=i;
            tmpMin=i;
        }
    }
    return make_pair(minIndex,maxIndex);
}
int main()
{
    int k;
    cin>>k;
    vector ivec;
    for(int i=0;i!=k;++i)
    {
        int t;
        cin>>t;
        ivec.push_back(t);
    }
    //考虑全为负值的特殊情况
    for(int i=0;i!=k;++i)
    {
        if(ivec[i]>=0)
        {
            break;
        }
        if(i==k-1)
        {
            cout<<"0 "< ret=findSubseq(ivec);
    int sum=0;
    for(int i=ret.first;i!=ret.second;++i)
    {
        sum+=ivec[i];
    }
    cout<

你可能感兴趣的:(甲级-1007 Maximum Subsequence Sum (25 分))