最大连续子序列和,以及开始、结束下标(HDU 1003)

 HDU1003

Problem Description
  Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
 
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
 
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
 
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
 
Sample Output
Case 1:
14 1 4
 
Case 2:
7 1 6
    求最大子序列的和,及其左右开始下标。
   甚是惭愧,现在是10月份,此题我在3月份已经在HDU上交过并AC了,但是没写题解,导致现在题出来又不会,现在必须补上。
   此前我想的是,遇到a[i]<0时,重新更新sum值,但是后来一想不对,比如这个 :  2  -1   100  更新sum的话,最大只能加到100而不是101.
   初始用dp保存输入的每个数字,而后的过程中,dp[i]为以 i 位置为结尾的最大值。如果走的过程中,dp[i-1]<0了,即累加出现<0的情况,那么就没必要再加了,因为再加就会减小。所以要从dp[i]重新累加,记录到此时的左端点  k=i;    每次for更新一次最大值(dp[i]>max),l=k,r=i;
    
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e5+10;
int dp[maxn];    //maxx=max{dp[i-1]+a[i],a[i]} 
int main()
{
    int t;
    cin>>t;
    int mid=t;
    int ac=1;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=1;i<=n;i++)
            cin>>dp[i];
        int maxx=dp[1];
        int l=1,r=1;
        int k=1;
        for(int i=2;i<=n;i++)
        {
        //    cout<<dp[i-1]<<endl;
            if(dp[i-1]>=0)
            {
                dp[i]+=dp[i-1];
            }
            else
            {
                k=i;
            }
            if(dp[i]>maxx)
            {
                maxx=dp[i];
                l=k;
                r=i;
            }
        }
        printf("Case %d:\n",ac);
        printf("%d %d %d\n",maxx,l,r);
        if(ac!=mid)
            cout<<endl;
        ac++;
    }
    return 0;
}

    注意输出,最后一句。每个样例之间输出一个空行,但是注意结尾不能有空行!

posted @ 2019-10-17 17:09  liyexin  阅读(422)  评论(0编辑  收藏  举报