hdu 4193 Non-negative Partial Sums (单调队列)

Non-negative Partial Sums
Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1357    Accepted Submission(s): 518


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

 

题意:

每次把最后一个元素移动到队首,求这n个数的所有前缀数组的和都>=0

算法参考:

以一个长度n为5的数串(-10,3,-1,5,4)为例,如下图:

为了简化操作,A[]和Sum[]的存储都从1开始,0下标位置的值都赋为0。 

 

A[]存储数字串以及它的一份拷贝,图中绿色方框为原数据(下标为1~n),黄色方框为拷贝(下标为n~2*n)。那么这个数串的一个序列就是图中红色方框圈起来的n个数,这里称红色方框为滑动窗口。

 

Sum[]存储一段数字的和,Sum[i]表示,A[1]~A[i]的和。如上图中Sum[3] = -10 + 3 + -1 = -8。

 

这里设S(i)为:假设滑动窗口的最后一个数的下标为就j,那么j-n+1 <= i <= j,S(i) = A[j-n+1] + A[j-n] + … + A[i]。题中要找满足滑动窗口内所有S(i) >= 0条件的序列,所以只需要找出最小的S(i),如果它的值都大于等于0的话,该序列就满足条件。使用单调递增队列来寻找最小的S(i)。

 

Sum[i]和S(i)的转化关系为:当前滑动窗口的末尾数的下标为j,S (i) =Sum[i] – Sum[j-n](其实这句话有点误导作用,请忽略就行)。

所以,我们在判断的时候,只需要判断 ( 最小的S(i))-Sum[j-n]是否大于等于0即可
 

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
const int N=2000005; ///注意开两倍的,不然会超时
deque<pair<int,int> >q;
int sum[N],v[N];
int main()
{
    int n; 
    while(~scanf("%d",&n)&&n)
    {
        q.clear();
        for(int i=1;i<=n;i++)
		{
			scanf("%d",&v[i]);
			v[i+n]=v[i];
			if(i==1)
				sum[i]=v[i];
			else
				sum[i]=sum[i-1]+v[i];
		}
		for(int i=n+1;i<=2*n;i++)
		{
			sum[i]=sum[i-1]+v[i];
		}
		int ans=0;
        for(int i=1;i<2*n;++i)
        {
            while(!q.empty()&&sum[i]<=q.back().first)
                q.pop_back();
            
            q.push_back(make_pair(sum[i],i));
            
            while(!q.empty()&&i-q.front().second>=n)  
                 q.pop_front();
			
			if(i>=n)
			{
				if(q.front().first-sum[i-n]>=0)
					ans++;
			}
		
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值