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>
#define pb push_back
#define fi first
#define se second
#define sz(x) (int)x.size()
#define cat(x) cerr << #x << " = " << x << endl
#define IOS cin.tie(0); ios_base::sync_with_stdio(0)
 
using ll = long long;
using namespace std;

const int N = 1 << 19;

int n, m;
ll a[N], b[N], f[N], dp[N];

void upd(int x, ll val) {
	x++;
	for (; x < N; x += x & -x)
		f[x] = min(f[x], val);
}

ll query(int x) {
	x++;
	ll res = N;
	for (; 0 < x; x -= x & -x)
		res = min(res, f[x]);
	return res;
}

int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i) {
		scanf("%lld", a + i);
		a[i] = a[i] + a[i - 1];
		b[i] = a[i];
	}
	sort(b, b + n + 1);
	m = unique(b, b + n + 1) - b;
	fill(f, f + m + 1, N);
	upd(lower_bound(b, b + m, 0) - b, 0);
	for (int i = 1; i <= n; ++i) {
		int p = lower_bound(b, b + m, a[i]) - b;
		dp[i] = i - 1 + query(p);
		upd(p, dp[i] - i);
	}
	if (dp[n] >= N) dp[n] = -1;
	printf("%lld\n", dp[n]);	
	return 0;
}