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

using namespace std;
long long n,dr,i,j,x,a;
long long dp[500005], tab[500005], droga[500005],pref[500005];
const int maks=500100;
int main ()
{
    ios_base::sync_with_stdio(false);
    cin>>n;
    for (i=1;i<=n;i++)
    {
        cin>>a;
        if (a!=0)
        {
            x++;
            dp[x]=maks;
            tab[x]=a;
            droga[x]=i;
            pref[x]=pref[x-1]+a;
        }
    }
    for (i=1;i<=x;i++)
    {
        if (pref[i]>=0)
        {
            dp[i]=droga[i]-droga[1];
        }
    }
    for (i=1;i<=x;i++)
    {
        for (j=2;j<=i;j++)
        {
            if (pref[i]-pref[j-1]>=0)
            {
                dp[i]=min(dp[i],droga[i]-droga[j]+dp[j-1]);
            }
        }
        //cout<<"dp="<<dp[i]<<"  droga[i]="<<droga[i]<<" pref[i]="<<pref[i]<<'\n';
    }
    if (dp[x]>=maks)
    {
        cout<<-1<<'\n';
    }
    else
    {
        cout<<dp[x]<<'\n';
    }
    return 0;
}