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
#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
#define pb push_back
typedef pair <int, int> pii;
typedef long long ll;
typedef double db;

const int N = 5e5;
const int MAX = (1 << 19);
const ll INF = 1e9;

int n, m, curr;
ll a[N + 5], tree[MAX + MAX + 5], pref[N + 5], dp[N + 5];
vector <ll> vec;

void Update(int x, ll v){
	x += MAX;
	tree[x] = v;
	x >>= 1;
	while(x){
		tree[x] = min(tree[x], v);
		x >>= 1;
	}	
}

ll Query(int x, int y){
	x += MAX;
	y += MAX;
	ll res = tree[x];
	if(x != y){
		res = min(res, tree[y]);
	}
	while(x / 2 != y / 2){
		if(!(x % 2)){
			res = min(res, tree[x + 1]);
		}
		if(y % 2){
			res = min(res, tree[y - 1]);
		}
		x >>= 1;
		y >>= 1;
	}
	return res;
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);	
	
	fill(tree, tree + MAX + MAX, INF);
	cin >> n;
	for(int i=1; i<=n; i++){
		cin >> a[i];
		pref[i] = a[i] + pref[i - 1];
		vec.pb(pref[i]);
	}
	if(pref[n] < 0){
		return cout << -1 << "\n", 0;
	}
	sort(vec.begin(), vec.end());
	vec.erase(unique(vec.begin(), vec.end()), vec.end());
	Update(lower_bound(vec.begin(), vec.end(), 0ll) - vec.begin(), 0ll);
	for(int i=1; i<=n; i++){
		curr = lower_bound(vec.begin(), vec.end(), pref[i]) - vec.begin();
		dp[i] = Query(1, curr) + i - 1;
		Update(curr, dp[i] - i);
	}
	cout << (dp[n] >= INF ? 0 : dp[n]) << "\n";
	
	return 0;
}