1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <bits/stdc++.h>
#define fi first
#define sc second
#define forn(i,p,k) for(int i=(p);i<=(k);++i)
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair<ll,int> pii;
const int MM=500013;
const int inf=1000000013;
inline void read(int &x)
{
    char c='*',f=0;
    for(;c<'0'||c>'9';c=getchar())  f-=(c=='-');
    for(x=0;'0'<=c&&c<='9';c=getchar()) x = (x<<3) + (x<<1) + c - '0';
    if(f)   x=(-x);
}
long long pre[MM];
int T[MM],dp[MM],Tr[MM],idx[MM],upp[MM];
vector< pii > V;
inline int Query(int x)
{
    int wyn=inf;
    for(;x>0;x-=(x&(-x)))   wyn=min(wyn,Tr[x]);
    return wyn;
}
inline void Upd(int x, const int &v)
{
    for(;x<MM;x+=(x&(-x)))  Tr[x]=min(Tr[x],v);
}
int main()
{
    ios_base::sync_with_stdio(0);
    size_t st = clock();
    int n;
    read(n);
    forn(i,1,n)
    {
        read(T[i]);
        pre[i]=pre[i-1]+T[i];
    }
    if(pre[n]<0)    return cout<<-1<<"\n",0;
    forn(i,1,n) V.pb({pre[n]-pre[n-i],n-i+1});
    sort(V.begin(),V.end(),[](const pii &a, const pii &b){return a>b;});
    forn(i,1,n) idx[V[i-1].sc]=i;
    memset(Tr,63,MM*sizeof(int));
    Upd(idx[1],0);
    forn(i,1,n) upp[i]=i;
    for(int i=n-2;i>=0;--i) if(V[i].fi==V[i+1].fi)  upp[i+1]=upp[i+2];
    forn(i,1,n)
    {
        int ind;
        if(i!=n)    ind = upp[idx[i+1]];
        else        ind = (upper_bound(V.begin(),V.end(),mp(0,0),[](const pii &a, const pii &b){return a>b;})-V.begin());
        dp[i] = Query(ind);
        dp[i]+=i-1;
        if(i!=n)    Upd(idx[i+1],dp[i]-i);
    }
    return cout<<dp[n]<<"\n",0;
}