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 0Sample Output
3 2 0n个数有多少种移位方式使得从第一个数往后加加到任意位置时和都不小于0,移位就是将第一个数字放到最后一个。
这道题没有那么复杂不用考虑线段树求区间最小值。从第n个数开始往前加,如果加到某个数字和是负数,那么这个数字肯定不能作为第一个数字,如果是正数那么这一段区间的和不会影响前面的区间,可以把和置为0,从前一个数重新开始加,因为是循环移位,最前面数字的加和可能会影响后面的数字,所以扫描两遍数组,最后扫描标记数组,一共有多少个数字可以作为第一个数。
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<stack>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const int INF = 0x3f3f3f3f;
int n,m;
int i,j,k;
int ans,res;
int a[1000010];
int cnt[1000010];
ll sum;
int main()
{
while(~scanf("%d",&n)&&n)
{
ans=0;
sum=0;
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
memset(cnt,0,sizeof cnt );
res=0;
for(i=n-1; ;i=(i+n-1)%n)
{
if(!i)
res++;
if(res==2)
break;
sum+=a[i];
if(sum<0)
cnt[i]=1;
else
sum=0;
}
for(i=0; i<n; i++)
{
if(!cnt[i])
ans++;
}
printf("%d\n",ans);
}
return 0;
}