最大连续子序列

给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ..., 
Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个, 
例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和 
为20。 
在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该 
子序列的第一个和最后一个元素。 

Input

测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( < 10000 ),第2行给出K个整数,中间用空格分隔。当K为0时,输入结束,该用例不被处理。 

Output

对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元 
素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。 

Sample Input

6
-2 11 -4 13 -5 -2
10
-10 1 2 3 4 -5 -23 3 7 -21
6
5 -8 3 2 5 0
1
10
3
-1 -5 -2
3
-1 0 -2
0

Sample Output

20 11 13
10 1 4
10 3 5
10 10 10
0 -1 -2
0 0 0


        
  
Huge input, scanf is recommended.

Hint

Hint
        
题意:求最长连续和,并且记录首尾

思路:dp[i][j]表示前j个数分成i段的最大值(i==1),加一个last数组记录得到最大值的最后一个数,然后到推一下就知道第一个了。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
#define inf 0x3f3f3f3f
int n;
int a[maxn];
int dp[maxn],g[maxn];
int len[maxn],last[maxn];
int main(int argc, char const *argv[])
{
     #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    while(scanf("%d",&n)!=EOF&&n)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        memset(dp,0,sizeof(dp));
        memset(g,0,sizeof(g));
        memset(last,0,sizeof(last));
        int mm;
        int tmp;
        if(n==1)
        {
            if(a[1]<=0)
            {
                printf("%d %d %d\n",0,a[1],a[1]);
            }
            else
            {
                printf("%d %d %d\n",a[1],a[1],a[1]);
            }
            continue;
        }
        for(int i=1;i<=1;i++)
        {
            mm=-inf;
            for(int j=1;j<=n;j++)
            {
                if(dp[j-1]>g[j-1])
                {
                    last[j]=j;
                }
                else last[j]=last[j-1];
                dp[j]=max(dp[j-1],g[j-1])+a[j];
                g[j-1]=mm;
                if(dp[j]>mm)
                {
                    tmp=last[j];
                }
                mm=max(mm,dp[j]);
            }
        }
        if(mm<0)
        {
            printf("%d %d %d\n",0,a[1],a[n]);
        }
        else if(mm==0)
        {
            printf("%d %d %d\n",0,0,0);
        }
        else{
        int r=a[tmp];
        int dd=mm;
        int l=tmp;
        while(dd!=0&&l>=0)
        {
            dd-=a[l];
            l--;
        }
        l=a[l+1];
        printf("%d %d %d\n",mm,l,r);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/81315389