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

ll val[500009];
ll pref[500009];
unordered_map<ll, ll> calc;

inline bool ok(int a, int b) {
    return (pref[b+1] - pref[a]) >= 0;
}

inline int cost(int a, int b) {
    return b - a;
}

ll solve(ll a, ll b) {
    if(not ok(a, b))
        return -1;
    ll res = cost(a, b);
    ll last = a;
    for(ll i = a + 1; i <= b; i++) {
        if(val[i] == 0)
            continue;

        if(ok(a, last) and ok(i, b)) {
            auto it = calc.find(1000000*i+b);
            if(it == calc.end())
                res = min(res, cost(a, last) + solve(i, b));
            else
                res = min(res, cost(a, last) + (*it).second);
        }

        last = i;
    }
    calc[1000000*a+b] = res;
    return res;
}

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

    int n;
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> val[i];
        pref[i+1] = pref[i] + val[i];
    }
    int a = 1, b = n;
    while(val[a] == 0 and a <= n)
        a++;
    if(a > n)
        cout << 0 << "\n";
    else {
        while(val[b] == 0)
            b--;
        cout << solve(a, b) << "\n";
    }

    return 0;
}