HDU 5783 Divide the Sequence

http://acm.split.hdu.edu.cn/showproblem.php?pid=5783

题意:
给出一段序列,现在要把它分成尽量多的连续序列,使得每一段序列之和都大于等于0。

思路:

做完之后去看别人的代码都是从后往前扫一遍就好了。

我自己写得稍微复杂了些吧,就是用栈来维护一下,分情况来进行入栈操作:

①如果第i个数为正数并且栈顶为正数,入栈。

②如果第i个数为正数并且栈顶为负数,将该数与栈顶值相加。

③如果第i个数为负数,与栈顶值相加,如果还是负的,继续与栈顶的下一个值相加,直到栈顶值为正或只剩下一个值。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<vector>
 6 #include<stack>
 7 #include<queue>
 8 #include<cmath>
 9 #include<map>
10 #include<set>
11 using namespace std;
12 typedef long long ll;
13 typedef pair<int,int> pll;
14 const int INF = 0x3f3f3f3f;
15 const int maxn = 1e6 + 5;
16 
17 int n;
18 int sta[maxn];
19 
20 int main()
21 {
22     //freopen("in.txt","r",stdin);
23     while(~scanf("%d",&n))
24     {
25         int top=0;
26         for(int i=0;i<n;i++)
27         {
28             int x; scanf("%d",&x);
29             if(top==0)  sta[++top]=x;
30             else
31             {
32                 if(x>=0)
33                 {
34                     if(sta[top]>=0)  sta[++top]=x;
35                     else sta[top]=sta[top]+x;
36                 }
37                 else
38                 {
39                     while(top)
40                     {
41                         sta[top]+=x;
42                         if(sta[top]>=0)  break;
43                         x=sta[top];
44                         top--;
45                     }
46                     if(top==0 && x<0)  sta[++top]=x;
47                 }
48             }
49         }
50         printf("%d
",top);
51     }
52     return 0;
53 }
原文地址:https://www.cnblogs.com/zyb993963526/p/7663015.html