HDU1231最大连续子序列的和

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e4+10;
int a[maxn];
int n;

void solve()
{
    int maxs = a[0],cnt = 0,l = a[0],r = a[0],t;
    /**maxs记录最大连续子序列之和**/
    /**cnt记录遍历到a[i]时,以a[i]结尾的子序列最大和**/
    for(int i = 0; i < n; ++i)
    {
        if(cnt < 0)/**以a[i-1]结尾的子序列和小于0**/
        {
            cnt = a[i];
            t = a[i];/**标记新的起点**/
        }
        else
            cnt += a[i];/**起点不变**/
        if(cnt > maxs)/**如果以a[i]结尾的最大子序列和超过前面的值**/
        {
            l = t;/**将cnt蕴含的起点,重点记录下来**/
            r = a[i];
            maxs = cnt;/**更新最大和**/
        }
    }
    if(maxs < 0)/**最大和小于0**/
    {
        printf("%d %d %d\n",0,a[0],a[n-1]);
    }
    else
        printf("%d %d %d\n",maxs,l,r);
}
int main()
{
    while(scanf("%d",&n))
    {
        if(n == 0)
            break;
        for(int i = 0; i < n; ++i)
            scanf("%d",&a[i]);
        solve();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41658955/article/details/87882194