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

using namespace std;

vector<pair<long long,int> > v1;
vector<pair<long long,int> > v2;
vector<pair<int,long long> > dp[500001];

int main()
{
   long long n,ds=0,ms=0,k,ok=-1,tp=-1,w=0;
   int nd;
    cin>>n;
    for(int i=0; i<n; i++){
        cin>>k;
        ds+=k;
        ms+=k;
        if(k!=0&&ok<0){
            ok=i;
        }
        if(tp<0&&k!=0){
            tp=i;
        }
        if(k!=0&&ds>=0){
            v1.push_back({ms,tp-ok});
            //cout<<tp<<" "<<ok<<endl;
            ok=i;
            w+=ok-tp;
            ms=0;
            tp=-1;
        }
    }
    //cout<<w<<endl;
    if(ds<0){
        cout<<-1;
        return 0;
    }
    //for(int i=0; i<v1.size(); i++){
        //cout<<v1[i].first<<" "<<v1[i].second<<endl;
    //}
    //cout<<endl;
    ms=0;
    ds=0;
    k=0;
    for(int i=v1.size()-1; i>=0; i--){
        ds+=v1[i].first;
        ms+=v1[i].first;
        if(ds>=0){
            //cout<<i<<endl;
            v2.push_back({ms,k});
            ms=0;
            k=v1[i].second;
        }else{
            w+=v1[i].second;
        }
    }
    //cout<<w<<endl;
    if(v1.empty()){
        cout<<0;
        return 0;
    }
    //for(int i=0; i<v2.size(); i++){
        //cout<<v2[i].first<<" "<<v2[i].second<<endl;
    //}
    //cout<<endl;
    dp[0].push_back({0,v2[0].first});
    //cout<<0<<" "<<0<<" "<<v2[0].first<<endl;
    nd=0;
    for(int i=1; i<v2.size(); i++){
        dp[i].push_back({nd,v2[i].first});
        //cout<<i<<" "<<nd<<" "<<v2[i].first<<endl;
        if(v2[i].first<0){
            nd=1e9;
        }
        for(int j=0; j<dp[i-1].size(); j++){
            dp[i].push_back({dp[i-1][j].first+v2[i].second,dp[i-1][j].second+v2[i].first});
            //cout<<i<<" "<<dp[i-1][j].first+v2[i].second<<" "<<dp[i-1][j].second+v2[i].first<<endl;
            if(dp[i-1][j].second+v2[i].first>=0){
                nd=min(nd,dp[i-1][j].first+v2[i].second);
            }
        }
    }
    cout<<w+nd;
}