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
#include<bits/stdc++.h>
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define pii pair<ll, ll>
#define pll pair<long long, long long>
#define ll long long
#define vi vector<ll>
#define vl vector<ll>
#define rep(i,p,k) for(ll i=p; i<k; i++)
#define per(i,p,k) for (ll i=k-1;i>=p;i--)

ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}

using namespace std;

ll tab[1000000];
ll tab2[1000000];
ll t[1000000];

ll INF = 2000000000;  //LONG LONG

int main() {
    ios_base::sync_with_stdio(0);
    ll n;
    cin >> n;
    vector<pll>v;
    ll zer = 0;
    ll m = 0;
    rep(i, 0, n) {
        cin >> tab[i];
        if (tab[i] == 0)
            zer++;
        else {
            v.pb(mp(zer+1, tab[i]));
            m++;
            zer = 0;
        }
    }
    rep(i, 1, m+1) {
        ll naj = INF;
        ll sum = 0;
        ll koszt = 0;
        rep(j, 0, i) {
            sum += v[i-j-1].s;
            if (sum >= 0) {
                naj = min(naj, koszt + t[i-j-1]);
            }
            koszt += v[i-j-1].f;
        }
        t[i] = naj;
    }
    cout<<t[m];
}