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
#include<bits/stdc++.h>
using namespace std;
int tab[1000005];
int pot = (1<<20);
int tree[3000005];
void ins(int a,int b)
{
    int pom = a + pot;
    while(pom != 0)
    {
        tree[pom] = min(tree[pom] , b);
        pom /= 2;
    }
}
int check(int a,int b)
{
    int l = a+pot , r = b+pot;
    int res = tree[l];
    if(l!=r)
        res = min(res , tree[r]);
    while(l/2!=r/2)
    {
        if(l%2==0)
            res = min(res , tree[l+1]);
        if(r%2==1)
            res = min(res , tree[r-1]);
        l/=2;
        r/=2;
    }
    return res;
}
vector<long long> v;
void przenumeruj()
{
    set<long long> s;
    for(auto x:v)
        s.insert(x);
    v.resize(0);
    for(auto x:s)
        v.push_back(x);
}
int f(long long x)
{
    return (lower_bound(v.begin(),v.end(),x) - v.begin());
}

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	//freopen("ele25.in","r",stdin);
	for(int x=0;x<=3000004;x++)
        tree[x] = 1e9+7;
    int a;
    cin>>a;
    long long sum = 0;
    for(int x=1;x<=a;x++)
    {
        cin>>tab[x];
        sum+=tab[x];
        v.push_back(sum);
    }
    v.push_back(-1e18);
    przenumeruj();
    sum = 0;
    ins(0,0);
    for(int x=1;x<=a;x++)
    {
        sum += tab[x];
        if(sum < 0)
            continue;
        int pom = f(sum);
        int pom2 = check(0,pom) + x - 1;
        ins(pom,pom2-x);
        if(x == a)
        {
            cout<<pom2;
            return 0;
        }
    }
    cout<<-1;
	return 0;
}