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

int main() {
	ios_base::sync_with_stdio(0);
	int n;
	cin >> n;
	vector<int> m,d;
	vector<long long> sl;
	int z=-1;
	long long S=0;
	for (int i=0;i<n;i++) {
		int a;
		cin >> a;
		z++; S+=a;
		if (a!=0) {
			m.push_back(a);
			d.push_back(z);
			sl.push_back(S);
			z=0;
		}
	}
	//for (int i=0;i<m.size();i++)
	//	cout << m[i] << " " << d[i] << " " << sl[i] << endl;
	//cout << S << endl;
	if (S<0) {cout << -1; return 0;}
	if (m.size()==0) {cout << 0; return 0;}
	vector<bool> e(m.size(),0); e[0]=e[e.size()-1]=1;
	int answer = 0;
	for (int i=0;i<m.size()-1;i++) {
		if (sl[i]<0 || S-sl[i]<0) {
			//cout << d[i+1];
			answer += d[i+1];
			e[i]=e[i+1]=1;
		}
		else {
			//cout << "-";
		}
	}
	//cout << endl;
	//for (int i=0;i<m.size();i++) cout << e[i]; cout << endl;
	int sd=-1,md;
	for (int i=0;i<m.size();i++) {
		if (m[i]<0 && !e[i]) {
			//cout << m[i] << endl;
			if (sd<0) {
				sd=d[i];
				md=d[i];
			} else {
				sd+=d[i];
				md=max(md,d[i]);
			}
		}
		else 
			if (sd>=0) {
				sd+=d[i];
				md=max(md,d[i]);
				//cout << "sd="<<sd<<" md="<<md<<endl;
				//cout << sd-md << endl;
				answer += sd-md;
				sd=-1;
			}
	}
	cout << answer;
	return 0;
}