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
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;