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
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

const int U = 1<<19;
int e[U+U];

void insert(int s, int w) {
	s += U;
	while(s) {
		e[s] = std::max(e[s], w);
	  s /= 2;
	}
}

int query(int s, int v = 1) {
	s += U;
	int ret = e[s];
	while(s > 1) {
		if (s % 2) {
			ret = std::max(ret, e[s-1]);
		}
		s /= 2;
	}
	return ret;
}

int main() {
	for (int i = 0; i < U+U; i++) e[i] = -1; 
  int n;
	scanf("%d",&n);
	vector<int> sp(n+1);
	{
		int tt;
		vector<long long> s(n+1);
		for (int i = 1; i <= n; i++) {
			scanf("%d", &tt);
			s[i] = s[i-1] + tt;
		}
		vector<long long> ss = s;
		sort(ss.begin(), ss.end());
		ss.erase(unique(ss.begin(), ss.end()), ss.end());
		for (int i = 0; i <= n; i++) {
			sp[i] = lower_bound(ss.begin(), ss.end(), s[i]) - ss.begin();
		}
	}
	vector<int> w(n+1);
	insert(sp[0], 0);
	for (int i = 1; i <= n; i++) {
	  /*w[i] = -1;
		for (int j = 0; j < i; j++) {
			if (s[i] >= s[j] && w[j] >= 0) {
		  	w[i] = std::max(w[i], w[j]+1);
			}
		}*/
		w[i] = query(sp[i]);
		if (w[i] >= 0) {
			w[i] += 1;
			insert(sp[i], w[i]);
		}
		//printf("%d :: %d\n",i,w[i]);
	}
	if (w[n] < 0) puts("-1");
	else printf("%d\n", n - w[n]);
	return 0;
}