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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <stdbool.h>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;

bool bDebug = !true;

class Point {
public:
	Point(int v, int p)
	{
		val = v;
		pos = p;
	}
	int val;
	int pos;
};

struct Query {
	int pos;
	int64_t ballance;
	bool bOn;
};

bool operator<(const Query& l, const Query& r) {
	if (l.pos      < r.pos     ) return true;
	if (l.pos      > r.pos     ) return false;
	if (l.ballance < r.ballance) return true;
	if (l.ballance > r.ballance) return false;
	if (l.bOn      < r.bOn     ) return true;
	if (l.bOn      > r.bOn     ) return false;
	return false;
}

vector<Point> points;
map<Query, int> m;

__inline int cost(int pos)
{
	return pos > 0 ? points[pos].pos - points[pos - 1].pos : 0;
}

int min_cost(int pos, int64_t ballance,bool on)
{
	Query q = { pos,ballance,on };

	if (m.find(q) != m.end()) return (int)m.find(q)->second;
	
	const int64_t v = points[pos].val + ballance;
	const int step_cost = (on ? cost(pos) : 0);

	if (pos == (int)points.size() - 1) 
	{
		if (v<0) return 999999999;
		return step_cost;
	}

	if (v == 0)
	{
		return step_cost + min_cost(pos + 1, 0, false);
	}
	else if (v<0)
	{
		return step_cost + min_cost(pos + 1, v, true);
	}
	
	const int a = step_cost + min_cost(pos + 1, 0, false);
	const int b = step_cost + min_cost(pos + 1, v, true);
	const int res = a < b ? a : b;

	m[q] = res;

	return res;
}

int main()
{
	int n;
	scanf("%d\n",&n);
	
	int64_t needs = 0;
	int64_t power = 0;
	
	points.reserve(5000);

	for (int i = 0; i < n; i++)
	{	
		int v;
		scanf("%d",&v);
		if (v > 0) power += v;
		if (v < 0) needs += v;
		if (v != 0) { points.push_back(Point(v, i)); }
	}

	if (power < needs)
	{
		printf("-1\n");	
		return 0;
	}

	int res = min_cost(0, 0, false);
	if (res >= 999999999)
	{
		printf("-1\n");
		return 0;
	}

	printf("%d\n", res);

	if (bDebug)
		while (true);

	return 0;
}