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

int n, a;
long long sum, wyn;
vector<pair <int, int>> droga;
queue <pair<int, int>> q;
int main() 
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	
	cin >> n; 

	for (int i = 0; i < n; i++)
	{
		cin >> a; 
		sum += a;
		if(a != 0)
			droga.push_back({ i+1,a }); 
	}

	if (sum < 0)
	{
		cout << "-1"; 
		return 0;
	}
	
	droga.push_back({ 0,droga[droga.size()-1].second }); 
	wyn =  droga[droga.size()-2].first - droga[0].first;
	
	int ile = 0, last = 0;
	int p = 0, k = 0;
	while(k < droga.size() - 2)
	{
		ile += droga[k].second; 
		if (ile > 0 && last < 0)
		{
			while(ile - droga[p].second > 0 && p <= k)
			{
				if (droga[p].second < 0)
					break;
				wyn -= droga[p + 1].first - droga[p].first;
				ile -= droga[p].second;
				p++;
			}
			p = k + 1;
			if(p != droga.size()-2)
				wyn -= droga[p].first - droga[p - 1].first;
			ile = 0;
		}
		last = ile;
		k++;
	}
	
	cout << wyn;

	return 0;
}