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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <bits/stdc++.h>

using namespace std;

#define st first
#define nd second
#define pb push_back
#define sz(x) (int)(x).size()
#define ll long long
int mod=1000000007;
int inf=1000000007;
ll infl=1000000000000000007;

ll a[500007];
vector<pair<ll,int>>suf;
ll s[500007];
int pos[500007];
pair<ll,int> seg[2000007];
int pot=1;
ll DP[500007];
set<pair<ll,int> >act;
pair<ll,int> que(int v,int a,int b,int l,int r)
{
    if(a<=l&&b>=r) return seg[v];
    if(r<a||l>b) return {infl,infl};
    pair<ll,int> p1=que(2*v,a,b,l,(l+r)/2);
    pair<ll,int> p2=que(2*v+1,a,b,(l+r)/2+1,r);
    if(p1.st<=p2.st) return p1;
    else return p2;
}
void ins(ll v,int u,int i)
{
    int y=i+pot-1;
    seg[y]={v,u};
    while(y>1)
    {
        y/=2;
        if(seg[2*y].st<=seg[2*y+1].st) seg[y]=seg[2*y];
        else seg[y]=seg[2*y+1];
    }
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    ll n;
    cin>>n;
    while(pot<n) pot*=2;
    for(int i=1;i<=n;i++) cin>>a[i];
    ll cur=0;
    for(int i=n;i>0;i--)
    {
        cur+=a[i];
        s[i-1]=cur;
        suf.pb({cur,i-1});
    }
    sort(suf.begin(),suf.end());
    for(int i=0;i<n;i++)
    {
        pos[suf[i].nd]=i+1;
    }
    for(int i=1;i<=2*pot;i++) seg[i]={infl,infl};
    ins(0,0,pos[0]);
    act.insert({s[0],pos[0]});
    act.insert({infl,infl});
    for(ll i=1;i<=n;i++)
    {
        DP[i]=infl;
        pair<ll,int>pr=*act.lower_bound({s[i],0});
        if(pr.st!=infl)
        {
            pr=que(1,pr.nd,n,1,pot);
            if(pr.st<=n) DP[i]=pr.st+i-1;
        }
        if(i!=n)
        {
            act.insert({s[i],pos[i]});
            ins(DP[i]-i,i,pos[i]);
        }
    }
    if(DP[n]>n) cout<<-1;
    else cout<<DP[n];

    return 0;
}