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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <cstdio>
#include <queue>
using namespace std;

int m[500002];
int w[500002];
int n,tmp;
int cnt = 0; 

struct node {
	int len = 0;
	long long value = 0;
	int cost = 1<<30; 
};


int main() {

	scanf("%d", &n);
	
	int prev_left = 0;

	for (int i=0;i<n;i++) {
		scanf("%d", &tmp);
		if (tmp !=0 ) {
			m[cnt] = tmp;
			w[cnt] = i - prev_left;
			prev_left = i;
			cnt ++;
		}
	}

	node start; 
	start.value = m[0];
	start.cost = 0;
	start.len = 1;

	queue<node> q,q2; 
	bool found = false;
	int low_cost = 1<<30;
	q.push(start);
	int last_len = 1;

	while (!q.empty()) {
		node a = q.front();
		q.pop();
		// printf("v:%d \t c:%d \tl:%d\n", a.value, a.cost, a.len);

		if(a.len != last_len) {
			last_len = a.len;
			if(!q2.empty()) {
				node min_q2 = q2.front();
				while (!q2.empty()) {
					node c = q2.front();
					if (c.cost < min_q2.cost) {
						min_q2 = c;
					}
					q2.pop();
				} 
				// printf("najmniejsze otwarcie: %d/%d\n", min_q2.value, min_q2.cost);
				q.push(min_q2);
			}
		}

		if( a.len == cnt) {
			if (a.value >=0 && a.cost < low_cost) {
				found = true;
				low_cost = a.cost;
			}
		} else {

			node x;
			// dokladam kolejny
			x.value = a.value + m[a.len];
			x.cost = a.cost + w[a.len];
			x.len = a.len +1;
			q.push(x);

			// otwieram nowa siec
			if( a.value >= 0) {
				node y;
				y.value = m[a.len];
				y.cost = a.cost;
				y.len = a.len + 1;
				q2.push(y);
			}
		}
	}

	if (found) {
		printf("%d\n", low_cost);
	} else {
		printf("-1\n");
	}

	
}