Non-negative Partial Sums
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1323 Accepted Submission(s): 508
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
Source
开2*n倍数组处理这种环形数据,求sum数组,现在就是求所有的长度为n的序列的sumi的最小值与这个序列前一个sum的差是否大于0,因为区间是单调递增的,所以单调队列之
郁闷的是这道水题居然写了一晚上T_T,太久没写题了
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int N = 1000100;
using namespace std;
int d[N+N],sum[N+N],q[N+N];
bool solve()
{
int n,lim=0;
scanf("%d",&n);
if(n==0)return false;
for(int i=1;i<=n;i++)
{
scanf("%d",&d[i]);
d[i+n]=d[i];
}
for(int i=1;i<=n+n;i++)
sum[i]=sum[i-1]+d[i];
int p1,p2,j,Ans=0;
p1=1;p2=0;
for(int i=1;i<n+n;i++)
{
//printf("i=%d q[p1]=%d\n",i,q[p1]);
while(p1<=p2 && sum[i]<sum[q[p2]])
p2--;
q[++p2]=i;
if(i>=n)
{
while(q[p1]<=i-n)p1++;
//printf("%d And %d\n",i-n,q[p1]);
if(sum[q[p1]]>=sum[i-n])
Ans++;
}
}
printf("%d\n",Ans);
return true;
}
int main()
{
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
while(solve());
return 0;
}