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
注意:
1、如果使用枚举遍历的方法,获得大小为n的数组的子数组个数的时间复杂度为O(n^2),然后计算子数组的时间复杂度为O(n),则总的时间复杂度为O(n^3),这种思路是不可取的
2、从左向右扫描,求出从临时起始点到当前点的的和,若为负数则重置临时起始点为当前值并重置临时和为0,若和更大,则更新起始点、结束点和最大和。
3、由于需要计算的数组为非全负,所以一定存在和为非负的子数组,所以遇到子数组和为负数的情况要重置临时起点。而之所以将临时起点重置,是因为所求的目标子数组的前几项的和肯定不是负数,否则去掉这几项那么该子数组的和会更大,而这样显然是不成立的。
4、以上分析可知,只有在子数组的和大于0并且和增长了的情况下才会更新目标子数组的结果,符合题意。

代码:
#include<iostream>
using namespace std;
 
const int INF_MIN = 0x80000000;
 
bool isAllNeg(int a[], int n)
{
    int i = 0;
    for(i=0; i<n; i++)
        if(a[i] >= 0)
            return false;
    return true;
}
 
int findMaxSubSeq(int a[],int n,int &b,int &e)
{
    int max = INF_MIN;
    int i = 0;
    int t1 = a[0];
    int t2 = a[0];
    int sum = 0;
    for(i=0; i<n; i++)
    {
        t2 = a[i];
        sum += a[i];
        if(sum > max)
        {
            b = t1;
            e = t2;
            max = sum;
        }
        if(sum < 0)
        {
            sum = 0;
            if(i < n-1)
                t1 = a[i+1];
                t2 = a[i+1];
        }
    }
    return max;
}
 
int main()
{
    int a[10000],n,i,b,e;
    scanf("%d",&n);
    for(i=0; i<n; i++)
        scanf("%d",&a[i]);
    if(isAllNeg(a,n))
    {
        cout<<0<<" "<<a[0]<<" "<<a[n-1]<<endl;
    }
    else
    {
        int minSum = findMaxSubSeq(a,n,b,e);
        cout<<minSum<<" "<<b<<" "<<e<<endl;
    }
     
    return 0;
}

你可能感兴趣的:(考试,pat,浙江大学)