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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#include <climits>
#include <iostream>
#include <numeric>
#include <vector>

using namespace std;

typedef unsigned long UINT;
typedef signed long SINT;
typedef unsigned long long UINT64;
typedef signed long long SINT64;

[[maybe_unused]] constexpr SINT MAX_SINT = LONG_MAX;
[[maybe_unused]] constexpr UINT MAX_UINT = ULONG_MAX;

// Benchmark
#ifdef LOCAL

static std::chrono::time_point<std::chrono::steady_clock> bench_start_time;
static vector<UINT> bench_analysis_levels;

void bench_on_exit()
{
	cout << flush;
	std::chrono::duration<double> bench_total;
	bench_total = chrono::steady_clock::now() - bench_start_time;
	cerr << "Analyzed nodes so many times, in shape of:" << endl;

	for (UINT i = 0; i < bench_analysis_levels.size(); i++) {
		cerr << " " << bench_analysis_levels[i];
	}
	cerr << endl;

	double total_calls = std::accumulate(bench_analysis_levels.begin(),
									   bench_analysis_levels.end(),
									   0.0);

	cerr << "Total analysis made: " << total_calls << endl;
	cerr << "Execution took " << bench_total.count() << " seconds." << endl;
}

#define BENCH_START \
	bench_start_time = chrono::steady_clock::now(); \
	atexit(bench_on_exit);

#else
#define BENCH_START
#endif
// End benchmark

/** Redirect stdin to provide input with Qt Creator */
void reopenInput(int argc, char** argv) {
#ifdef LOCAL
	if (argc > 1) {
		auto inFile = argv[1];
		cerr << "Reopening stdin to: " << inFile << endl;
		auto success = freopen(inFile, "r", stdin);
		if (!success) {
			cerr << "Error when opening file!" << endl;
			cerr << std::strerror(errno) << endl;
		}
	}
#endif
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

#undef VERBOSE

static SINT64 grid_surplus;

// Industrialized city (grid node)
struct Node {
	// distances to neighbouring nodes
	UINT distLeft = 0;
	UINT distRight = 0;

	// power in the node
	SINT power = 0;

	SINT64 surplus_on_left = 0;

	/// Tests whether connection with the previous grid node is required.
	bool inline canStartIsland() {
		return(this->surplus_on_left >= 0
			   &&
			   this->surplus_on_left <= grid_surplus);
	}
};

#define PRINT_NODE(node) node.power << " MW, " \
						 << node.distLeft << " away from previous and " \
						 << node.distRight << " from next, "

// Description of one or more islands analyzed
struct Islands {
	bool defined = false;
	UINT cost = 0;
	SINT power_lost = 0;
};

typedef vector<Node> Grid;

constexpr UINT NOT_FOUND = MAX_UINT;

static vector<SINT> cities;
static vector<Islands> islands;
static Grid grid;
static UINT n;

static UINT deliberate_costs = 0;
static UINT last_factory_at = NOT_FOUND;

[[ noreturn ]]
void fail()
{
	cout << -1 << endl;
	exit(0);
}

[[ noreturn ]]
void success(UINT cost)
{
	UINT total_cost = cost + deliberate_costs;
	cout << total_cost << endl;
	exit(0);
}

void processInput()
{
	cin >> n;
	cerr << "N: " << n << endl;
	cities.resize(n);

	for (UINT i = 0; i < n; i++) {
		cin >> cities[i];
#ifdef VERBOSE
		cerr << "  City " << i+1 << ": " << cities[i] << endl;
#endif
	}
}

// O(n)
void compactData()
{
	cerr << "Compacting data" << endl;

	grid.reserve(cities.size());

	UINT distance = 0;

	for (auto &cityPower : cities) {
		if (cityPower == 0) {
			distance++;
		} else {
			Node node;
			node.power = cityPower;
			node.distLeft = distance;
			grid.push_back(node);

			if (grid.size() > 1) grid[grid.size() - 2].distRight = distance;

			distance = 1;
		}
	}

#ifdef VERBOSE
	for (UINT i = 0; i < grid.size(); i++) {
		auto &node = grid[i];
		cerr << "  Electric city " << i << ": " << PRINT_NODE(node) << endl;
	}
#endif
}

// O(n)
void makeDeliberateConnections()
{
	// Merge rightmost energy consuming nodes
	while (grid.size() > 2) {
		Node &last = grid[grid.size() - 1];

		if (last.power > 0) break;

		Node &prev = grid[grid.size() - 2];
		prev.power += last.power;
		deliberate_costs += prev.distRight;
		prev.distRight = 0;
		grid.pop_back();

#ifdef VERBOSE
		cerr << "Merging last two nodes, new one is: "
			 << PRINT_NODE(prev) << endl;
#endif
	}
}



void analyze(UINT grid_idx, UINT cost, SINT64 curr_surplus, Islands &retval)
{
#ifdef LOCAL
	bench_analysis_levels[grid_idx]+=1;
#endif

	Node &curr_node = grid[grid_idx];
	Islands& next_islands = islands[grid_idx + 1];

	curr_surplus += curr_node.power;

	if (grid_idx >= grid.size() - 1) { // last
//		Islands finalIsle;
		retval.cost = cost;
		retval.defined = true;
		retval.power_lost = curr_surplus;
		return;
	}


	SINT64 power_lost_on_cut = curr_surplus + next_islands.power_lost;

	// try connecting next node and set analysis result to retval
	analyze(grid_idx + 1, cost + curr_node.distRight, curr_surplus, retval);

	// try making a cut
	if (curr_surplus >= 0 && next_islands.defined && power_lost_on_cut <= grid_surplus) {
		auto new_islands_cost = next_islands.cost + cost;

		if (new_islands_cost < retval.cost) {
			retval.cost = new_islands_cost;
			retval.power_lost = power_lost_on_cut;
			retval.defined = true;
		}
	}
}

[[ noreturn ]]
void analyzeGrid()
{
	islands.resize(grid.size() + 1); // with trailing (guard) empty island
	islands[grid.size()].defined = true; // mark guard as defined

	for (UINT j = grid.size(); j-- > 0; ) { // from last to first
		if (!grid[j].canStartIsland()) continue;
		analyze(j, 0, 0, islands[j]);
	}

	if (islands[0].defined) {
		success(islands[0].cost);
	} else {
		cerr << "SHOULD NEVER HAPPEN!!!";
		fail();
	}
}

[[ noreturn ]]
int main(int argc, char** argv)
{
	BENCH_START
	reopenInput(argc, argv);
	processInput();
	compactData();
	makeDeliberateConnections();

	// Calculate grid surplus and last factory index
	for (UINT i = 0; i < grid.size(); i++) {
		auto &node = grid[i];
		node.surplus_on_left = grid_surplus;
		grid_surplus += node.power;
		if (node.power < 0) last_factory_at = i;
	}

#ifdef LOCAL
	bench_analysis_levels.resize(grid.size());
#endif

	// Easy answers
	if (grid_surplus < 0) {
		cerr << "Not enough power: " << grid_surplus << " MW" << endl;
		fail();
	}
	if (last_factory_at == NOT_FOUND) {
		cerr << "There aren't any factories." << endl;
		success(0);
	}

#ifdef VERBOSE
	for (UINT i = 0; i < grid.size(); i++) {
		auto &node = grid[i];
		cerr << "  Electric city " << i << ": " << PRINT_NODE(node) << endl;
	}
#endif

	cerr << "Electric cities: " << grid.size() << endl;
	cerr << "Surplus power: " << grid_surplus << " MW" << endl;
	cerr << "Last factory: " << PRINT_NODE(grid[last_factory_at]) << endl;
	cerr << flush;

	analyzeGrid();
}