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

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define VAR(v,w) __typeof(w) v=(w)
#define SD second
#define INT(x) int x; scanf("%d", &x)
#define LLG(x) LL x; scanf("%lld", &x)

typedef long long LL;

int main() {
	INT(n);
	LL sb = 0;
	int cb = 0;
	map<LL, int> m;
	REP(i,n) {
		LLG(a);
		if (!i) {
			m[a] = 0;
			continue;
		}
		VAR(it,m.lower_bound(-sb));
		bool found = it != m.end();
		int ic = 0;
		if (found) ic = it->SD + cb;
		++cb;
		sb += a;
		if (!found) continue;
		LL x = a - sb;
		int y = ic - cb;
		VAR(jt,m.lower_bound(x));
		if (jt == m.end()) continue;
		if (jt->SD <= y) continue;
		m[x] = y;
		for (;;) {
			VAR(kt,m.find(x));
			if (kt == m.begin()) break;
			--kt;
			if (kt->SD < y) break;
			m.erase(kt);
		}
	}
	VAR(it,m.lower_bound(-sb));
	if (it != m.end()) printf("%d\n", it->SD + cb);
	else printf("-1\n");
}