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
#include <bits/stdc++.h>
using namespace std;

int n, t[500005], pref[500005], wyn, tu=1, a, ost=0, L, P, S, kon=1;
pair <int , int> p[500005];

int BS (int x){
    L=0;
    P=kon;
    while(L+1<P){
        S=(L+P)/2;
        if (t[S]>=x){
            P=S;
        }
        else {
            L=S;
        }
    }
    return P;
}

int main(){
    ios_base::sync_with_stdio(0);
    cout.tie(0);
    cin.tie(0);

    cin>>n;

    for (int i=1; i<=n; i++){
        cin>>a;
        if (a!=0){
            t[1]=tu;
            pref[tu]=pref[tu-1]+a;
            if (tu>1){
                p[tu]=make_pair(-1*(i-ost), tu);
            }
            else {
                wyn-=i;
            }
            ost=i;
            tu++;
        }
    }

    if (pref[tu-1]<0){
        cout<<-1;
        return 0;
    }

    if (tu==1){
        cout<<0;
        return 0;
    }

    sort (p+1, p+tu);

    wyn+=ost;
    t[0]=-1;

    for (int i=1; i<tu; i++){
        a=BS(p[i].second);
        if (pref[p[i].second-1]-pref[t[a-1]+1]>=0&&pref[t[a]]-pref[p[i].second-1]>=0){
            wyn+=p[i].first;
            for (int j=kon+1; j>a; j--){
                t[j]=t[j-1];
            }
            t[a]=p[i].second;
            kon++;
        }
    }

    cout<<wyn;

    return 0;
}