【HDU】4193Non-negative Partial Sums(单调队列求可行区间数量)

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3710    Accepted Submission(s): 1212


 

Problem Description

You are given a sequence of n numbers a0,..., an-1. A cyclic shift by k positions (0<=k<=n-1) results in the following sequence: ak ak+1,..., an-1, a0, a1,..., ak-1. How many of the n cyclic shifts satisfy the condition that the sum of the fi rst i numbers is greater than or equal to zero for all i with 1<=i<=n?

 

 

Input

Each test case consists of two lines. The fi rst contains the number n (1<=n<=106), the number of integers in the sequence. The second contains n integers a0,..., an-1 (-1000<=ai<=1000) representing the sequence of numbers. The input will finish with a line containing 0.

 

 

Output

For each test case, print one line with the number of cyclic shifts of the given sequence which satisfy the condition stated above.

 

 

Sample Input

 

3 2 2 1 3 -1 1 1 1 -1 0

 

 

Sample Output

 

3 2 0

 

 

Source

SWERC 2011

 

 

Recommend

lcy   |   We have carefully selected several similar problems for you:  4190 4192 4187 4188 4189 

 

 

题目大意:给你一个长度为N的数组,也就代表了类似于一个环装的,从中间取一个长度为N的序列,让他其中的所有的前缀和不会出现<0的情况,

思路:首先的话,如果这个序列的和本身就是负值,那么一定是没有任何的循环排列方式让他满足题意的,也就是输出答案0,

如果当前的长度为N的序列满足题中条件,那么我们可以只将最后的元素放到首位,如果移动前序列满足条件,则此次移动后得到的序列是否满足条件便由此元素决定。

如果这个元素 >= 0,那么这次移动得到的新队列同样满足题中的条件,ans++, 如果这个元素 < 0,则再次移动并累加移动元素值,直到某次移动后这个累计值 >= 0,此时ans可以+1,并且要把这个累计值清零。

代码:

#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cstdio>
using namespace std;
int a[1000010];
int main()
{
    int n;
    while(scanf("%d",&n)&&n)
    {
        int flag=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            flag+=a[i];
        }
        if(flag<0)
        {
            cout<<0<<endl;
            continue;
        }

        int l=0,pos=n,sum=0,ans=0;
        while(l<=pos)
        {
            sum+=a[l];
            l++;
            while(sum<0)
            {
                sum+=a[pos];
                pos--;
            }
        }
        int tmp=0;
        while(pos>=1)
        {
            if(tmp>=0) ans++;
            if(tmp<0) tmp+=a[pos];
            else if(a[pos]<0) tmp=a[pos];
            pos--;
        }
        printf("%d\n",ans);
    }
    return 0;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值