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
#include<bits/stdc++.h>
using namespace std;
using lld = long long;

const lld INF = 1e16;

struct ST{
	vector<lld> tree;
	int base;

	ST(int n=(1<<20)): base(1) {
		while(base < n)
			base <<= 1;

		tree.assign(2*base,INF);
	}

	void insert(int x, lld val){
		x += base;
		tree[x] = val;
		while(x > 1){
			x /= 2;
			tree[x] = min(tree[2*x],tree[2*x+1]);
		}
	}

	lld query(int b, int e){
		b += base, e += base;
		lld val = min(tree[b], tree[e]);

		while(b/2 != e/2){
			if(!(b&1))
				val = min(val, tree[b+1]);
			if(e&1)
				val = min(val, tree[e-1]);
			b /= 2, e /= 2;
		}

		return val;
	}
};

int main(void){
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);

	int n;
	cin >> n;

	vector<lld> t(n);
	for(lld& i : t)
		cin >> i;

	vector<lld> p(n+1,0);
	for(int i=0;i<n;i++)
		p[i+1] = p[i]+t[i];

	if(p[n] < 0){
		cout << "-1\n";
		return 0;
	}

	vector<pair<lld,int> > ord(n+1);
	for(int i=0;i<=n;i++)
		ord[i] = {p[i], i};

	sort(ord.begin(), ord.end());

	ST dp(n+1);
	for(auto [pref, i] : ord){
		if(i == 0){
			dp.insert(i,-1);
			continue;
		}

		lld val = dp.query(0,i-1)+i;
		dp.insert(i,val-(i+1));
	}

	cout << dp.query(n,n)+(n+1) << "\n";

	return 0;
}