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
85
86
87
88
89
90
91
92
93
94
#include <bits/stdc++.h>

using namespace std;

typedef long long int LL;

const int N = 5e5 + 7;
const int T = 1 << 19;
const int INF = 1e9 + 7;

int n;
int order[N];
int input[N];

int dp[N];
int tree[T + T];

void get_order() {
	LL sum = 0;
	map <LL, int> M;
	vector <LL> pref = {0};
	
	for (int i = 1; i <= n; ++i) {
		sum += input[i];
		pref.push_back(sum);
	}
	
	sort(pref.begin(), pref.end());
	pref.erase(unique(pref.begin(), pref.end()), pref.end());
	
	for (int i = 0; i < (int)pref.size(); ++i)
		M[pref[i]] = i;
	
	sum = 0;
	order[0] = M[sum];

	for (int i = 1; i <= n; ++i) {
		sum += input[i];
		order[i] = M[sum];
	}
}

void read() {
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i)
		scanf("%d", &input[i]);
	get_order();
}

void update(int p, int v) {
	p += T;
	while(p) {
		tree[p] = min(tree[p], v);
		p >>= 1;
	}
}

int ask(int from, int to) {
	int ret = INF;
	from += T, to += T;

	while(from <= to) {
		if(from & 1)
			ret = min(ret, tree[from]);
		
		if(!(to & 1))
			ret = min(ret, tree[to]);
		
		from = (from + 1) >> 1;
		to = (to - 1) >> 1;
	}
	
	return ret;
}

void solve() {
	for(int i = 1; i < T + T; ++i)
		tree[i] = INF;

	dp[0] = 0;
	update(order[0], dp[0]);
	
	for(int i = 1; i <= n; ++i) {
		dp[i] = i + ask(0, order[i]) - 1;
		update(order[i], dp[i] - i);
	}
}

int main() {
	read();
	solve();
	printf("%d\n", dp[n] > n ? -1 : dp[n]);
	return 0;
}