HDU 5783 Divide the Sequence

题意:求一个序列的分段个数,使得每一段的前缀和为0;

分析:如果正向思维,那么解法是从前往后遍历,每遇到一个负数就向前遍历直到>=0(这样贪心保证了序列尽可能多),但是这样最坏的情况是n^2的,所以要逆过来来考虑,每遇到负数就向前加到>=0即可,然后边统计答案,在n的算法里计算出。(注意:前缀和可能超int,用long long 保存)

输入:

6
1 2 3 4 5 6
4
1 2 -3 0
5
0 0 0 0 0

输出:

6
2
5

code:

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N=1e6+6;

ll v[N];

int main()

{

      int n;

      while (~scanf("%d",&n)){

           for (int i=0;i<n;i++) scanf("%lld",v+i);

           ll s=0,ans=0;

           for (int i=n-1;i>=0;i--){

                 s+=v[i];

                 if (s>=0) {ans++;s=0;}

           }

           cout<<ans<<endl;

      }

}

原文地址:https://www.cnblogs.com/137033036-wjl/p/5745842.html