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
#include <bits/stdc++.h>

using namespace std;

int n, sum;
vector<long long> v, pref = { 0 };
vector<pair<int, int> > edge;
set<pair<int, int>, greater<pair<int, int> > > odp;

struct len
{
	bool operator()(const pair<int, int>& a, const pair<int, int>& b)
	{
		return a.second - a.first > b.second - b.first;
	}
};

int main()
{
	cin >> n; v.resize(n);
	for (long long& i : v)
	{
		cin >> i;
		pref.push_back(pref.back() + i);
	}
	if (pref.back() < 0)
	{
		cout << "-1\n";
		return 0;
	}
	int e = -1, b = -1;
	for (int i = 0; i < n; i++)
	{
		if (v[i])
		{
			if (e == -1)
				b = i;
			else
				edge.push_back(make_pair(e, i));
			e = i;
		}
	}
	sort(edge.begin(), edge.end(), len());

	sum = e - b;
	odp.insert(make_pair(b, e));
	for (pair<int, int>& i : edge)
	{
		set<pair<int, int>, greater<pair<int, int> > >::iterator s = odp.lower_bound(make_pair(i.first, n + 1));
		if (pref[i.first + 1] - pref[s->first] >= 0LL && pref[s->second + 1] - pref[i.second] >= 0LL)
		{
			odp.insert(make_pair(s->first, i.first));
			odp.insert(make_pair(i.second, s->second));
			odp.erase(s);
			sum -= i.second - i.first;
		}
	}
	cout << sum << '\n';
}