Problem Description
Alice has a sequence A, She wants to split A into as much as possible continuous subsequences, satisfying that for each subsequence, every its prefix sum is not small than 0.
Input
The input consists of multiple test cases.
Each test case begin with an integer n in a single line.
The next line contains n integers A1,A2⋯An.
1≤n≤1e6
−10000≤A[i]≤10000
You can assume that there is at least one solution.
Output
For each test case, output an integer indicates the maximum number of sequence division.
Sample Input
6
1 2 3 4 5 6
4
1 2 -3 0
5
0 0 0 0 0
Sample Output
6
2
5
思路: 把长度为n的序列分成尽量多的连续段,使得每一段的每个前缀和都不小于0。保证有解。 从后往前贪心分段即可。此题我想了两种不同的解法,归根到底也都是贪心
#include<stdio.h>
#include<iostream>
using namespace std;
#include<string.h>
const int N=1e6+10;
__int64 a[N];
int main()
{
int n,m,k;
while(scanf("%d",&n)!=-1)
{
for(int i=0; i<n; i++)
scanf("%lld",&a[i]);
int sum=0;
for(int i=n-1; i>=0; i--)
{
if(a[i]>=0)
{
sum++;
}
else if(a[i]<0)
{
a[i-1]=a[i-1]+a[i];
}
}
printf("%d\n",sum);
}
}
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
const int N=1e6+10;
int a[N];
__int64 sum[N];
int n;
int main()
{
int i,j;
while(~scanf("%d",&n))
{
sum[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
int now=sum[n];
int cnt=1;
for(i=n-1;i>=1;i--)
{
if(sum[i]<=now&&sum[i]>=0)
{
now=sum[i];
cnt++;
}
}
printf("%d\n",cnt);
}
return 0;
}