HDU 1193 Non-negative Partial Sums / 单调队列

Non-negative Partial Sums

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)


Problem Description
You are given a sequence of n numbers a 0,..., a n-1. A cyclic shift by k positions (0<=k<=n-1) results in the following sequence: a k a k+1,..., a n-1, a 0, a 1,..., a k-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<=10 6), the number of integers in the sequence. The second contains n integers a 0,..., a n-1 (-1000<=a i<=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

 

给你一个n项的序列,每次可以把序列的首项移动到末尾,求有多少种序列的前i项和都大于等于0
首先将序列1-n扩大一倍 拿它自己拼接到后面

转换为前缀和 要求和大于0 可以用单调队列维护一个最小值 最小值大于0 说明的都是大于0

求每一段的前缀和和 比如x-y 那么可以sum(y)-sum(x-1) 开始预处理好

只不过把原本序列变成了前缀和

#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1000010;
int a[maxn*2];
int q[maxn*2];
int main()
{
    int n;
    while(scanf("%d", &n) && n)
    {
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &a[i]);
            a[i+n] = a[i];
        }
        int cnt = 0;
        for(int i = 1; i <= 2*n; i++)
            a[i] += a[i-1];
        int front = 0, rear = -1;
        
        for(int i = 1; i < 2*n; i++)
        {
            while(front <= rear && i - q[front] >= n)
                front++;   
            while(front <= rear && a[i] <= a[q[rear]])
                rear--;
            q[++rear] = i;
            if(i >= n && a[q[front]] - a[i-n] >= 0)
                cnt++;
        }
        printf("%d\n", cnt);
    }
    return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值