HDU-5783 Divide the Sequence(贪心)

题目大意:给一个整数序列,将其划分成若干个子连续序列,使其每个子序列的前缀和不为负。求最大的划分个数。

题目分析:从后往做累加计算,如果不为负,则计数加一,累加和清0。否则,一直往前扫描。如果最终的和为负,答案为0,否则为计数结果。

代码如下:

# include<iostream>
# include<cstdio>
# include<algorithm>
using namespace std;
# define LL long long

const int N=1000000;

int a[N+5];

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;++i)
            scanf("%d",a+i);
        int ans=0;
        LL sum=0;
        for(int i=n-1;i>=0;--i){
            sum+=(LL)a[i];
            if(sum>=0){
                ++ans;
                sum=0;
            }
        }
        if(sum<0) cout<<0<<endl;
        else cout<<ans<<endl;
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/20143605--pcx/p/5744319.html