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
#include <bits/stdc++.h>
#define PB push_back
#define ST first
#define ND second
#define _ ios_base::sync_with_stdio(0); cin.tie(0);
//mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());

using namespace std;

using ll = long long;
using pi = pair<int,int>;
using vi = vector<int>;

const int nax = 500 * 1000 + 10;
int n;
int A[nax];
map<ll, int>sc;
int nr;
int T[(1<<20)], R;

void upd(int a, int x) {
	a += R;
	T[a] = max(T[a], x);
	while(a > 1) {
		a/=2;
		T[a] = max(T[2*a], T[2*a+1]);
	}
}

int qr(int a, int b) {
	a += R; b += R;
	int w = max(T[a], T[b]);
	while(a/2 != b/2) {
		if(a % 2 == 0) w = max(w, T[a+1]);
		if(b % 2 == 1) w = max(w, T[b-1]);
		a/=2;
		b/=2;
	}
	return w;
}

int main() {_
	cin >> n;
	sc[0];
	ll sum = 0;
	for(int i = 1; i <= n; ++i) {
		cin >> A[i];
		sum += A[i];
		sc[sum];
	}
	if(sum < 0) {
		cout << "-1";
		return 0;
	}
	for(auto &it : sc) it.ND = nr++;
	R = 1;
	while(R <= nr) R *= 2;
	sum = 0;
	int ans = -1;
	for(int i = 1; i <= n; ++i) {
		sum += A[i];
		if(sum < 0) {
			continue;
		}
		int x = sc[sum];
		int w = qr(0, x);
		//~ cout << w + 1 << " ";
		ans = w + 1;
		upd(x, w + 1);
	}
	cout << n - ans;
}