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
#pragma GCC optimize ("O3")
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
const int INF = 0x3f3f3f3f;

#define FOR(i,b,e) for(int i = (b); i < (e); i++)
#define TRAV(x,a) for(auto &x: (a))
#define SZ(x) ((int)x.size())
#define PB push_back
#define X first
#define Y second

const int N = 5e5+5;
#define LSB(x) ((x)&(-x))

int dp[N], t[N], tree[N+1];
ll pref[N];

int sum(int x){
    int sum = INF;
    while(x > 0) sum = min(sum, tree[x]), x -= LSB(x);
    return sum;
}

void add(int x, int v){
    while (x <= N) tree[x] = min(tree[x], v), x += LSB(x);
}

void readInt(int &x){
    x = 0;
    char c = getchar();
    bool negative = 0;
    while(c < 33) c = getchar();
    if(c == '-') negative = 1, c = getchar();
    while('0' <= c && c <= '9') x = 10*x + c - '0', c = getchar();
    if(negative) x *= -1;
}

void solve(){
    int n; readInt(n);
    FOR(i, 1, n+1) readInt(t[i]);
    FOR(i, 1, n+1) pref[i] = pref[i-1] + t[i];
    vector<pair<ll, int>> ev;
    FOR(i, 0, n+1) if(pref[i] >= 0) ev.PB({pref[i], i});
    sort(ev.begin(), ev.end());
    memset(tree, INF, sizeof(tree));
    memset(dp, INF, sizeof(dp));
    TRAV(x, ev){
        dp[x.Y] = sum(x.Y+1) + x.Y - 1;
        if(x.Y == 0) dp[x.Y] = 0;
        add(x.Y+1, dp[x.Y]-x.Y);
    }
    cout << (dp[n] >= INF/2 ? -1 : dp[n]) << '\n';
}

int main(){
    // ios::sync_with_stdio(0);
    // cin.tie(0);
    // int tt; cin >> tt;
    // FOR(te, 0, tt)
    solve();
    return 0;
}