Divide the Sequence
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1462 Accepted Submission(s): 693
Each test case begin with an integer n in a single line.
The next line contains n
1≤n≤1e6
−10000≤A[i]≤10000
You can assume that there is at least one solution.
6 1 2 3 4 5 6 4 1 2 -3 0 5 0 0 0 0 0
6 2 5
题意分析:把长度为n的序列分成尽量多的连续段,使得每一段的每个前缀和都不小于0。保证有解。
从后往前贪心分段即可。大于等于0的为一段,遇到负数就一直相加到非负为止!(注意精度问题 用long long)
AC代码:
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
typedef long long LL;
const int N=1000010;
int a[N];
int main()
{
LL n,i;
while(scanf("%lld",&n)!=EOF)
{
for(i=1;i<=n;i++)
scanf("%lld",&a[i]);
LL sum=0;
for(i=n;i>=1;i--)
{
sum+=a[i];
if(sum>=0)
sum=0;
else n--;
}
printf("%lld\n",n);
}
return 0;
}