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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#include <cstdio>
#include <set>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <string.h>
#include <stdio.h>

// TODO: Maybe comment this out before submit.
//#define DBG_CHECKS
//#define DBG_FULL

#ifdef DBG_FULL
#include <sys/types.h>
#include <unistd.h>
#endif


// TODO: UWAGA NA TO PRZED WYSLANIEM
#include "message.h"
#include "krazki.h"

#define deb(x) cout << #x << " = " << x << endl;

using namespace std;

// Dwa z najczesciej uzywanych typow o dlugich nazwach
// - ich skrocenie jest bardzo istotne
typedef vector<int> VI;
typedef long long LL;

// W programach bardzo rzadko mozna znalezc w pelni zapisana instrukcje petli.
// Zamiast niej wykorzystywane sa trzy nastepujace makra:
// FOR - petla zwiekszajaca zmienna x od b do e wlacznie
#define FOR(x, b, e) for(int x = b; x <= (e); ++x)
// FORD - petla zmniejszajaca zmienna x od b do e wlacznie
#define FORD(x, b, e) for(int x = b; x >= (e); --x)
// REP - petla zwiekszajaca zmienna x od 0 do n. Jest ona bardzo czesto
// wykorzystywana do konstruowania i przegladania struktur danych
#define REP(x, n) for(int x = 0; x < (n); ++x)
// Makro VAR(v,n) deklaruje nowa zmienna o nazwie v oraz typie i wartosci
// zmiennej n. Jest ono czesto wykorzystywane podczas operowania na
// iteratorach struktur danych z biblioteki STL, ktorych nazwy typow sa bardzo dlugie
#define VAR(v, n) __typeof(n) v = (n)
// ALL(c) reprezentuje pare iteratorow wskazujacych odpowiednio na pierwszy
// i za ostatni element w strukturach danych STL. Makro to jest bardzo
// przydatne chociazby w przypadku korzystania z funkcji sort, ktora jako
// parametry przyjmuje pare iteratorow reprezentujacych przedzial
// elementow do posortowania
#define ALL(c) (c).begin(), (c).end()
// Ponizsze makro sluzy do wyznaczania rozmiaru struktur danych STL.
// Uzywa sie go w programach, zamiast pisac po prostu x.size() ze wzgledu na to,
// iz wyrazenie x.size() jest typu unsigned int i w przypadku porownywania
// z typem int w procesie kompilacji generowane jest ostrzezenie
#define SIZE(x) ((int)(x).size())
// Bardzo pozyteczne makro sluzace do iterowania po wszystkich elementach
// w strukturach danych STL
#define FOREACH(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
// Skrot - zamiast pisac push_back podczas wstawiania elementow na koniec
// struktury danych, takiej jak vector, wystarczy napisac PB
#define PB push_back
// Podobnie - zamiast first bedziemy pisali po prostu ST
#define ST first
// a zamiast second - ND
#define ND second

struct Sharding {
	int usedNodes;
	int d, n;
	Sharding(int n) {
		this->n = n;
		usedNodes = min(NumberOfNodes(), n);
		d = n / usedNodes;
	}

	int ShardCnt() {
		return usedNodes;
	}

	void GetRange(int nr, int &begin, int &end) {
		// if nr == 0, (0, k)
		// if nr == Last() (s, n)
#ifdef DBG_CHECKS
		if (nr > usedNodes - 1) cerr << "ERROR: nr > usedNodes - 1" << endl;
#endif
		begin = nr * d;
		end = (nr + 1) * d;
		if (nr == usedNodes - 1)
			end = n;
	}

	void MyRange(int &begin, int &end) {
		GetRange(MyNodeId(), begin, end);
	}

	bool ImUsed() {
		return MyNodeId() < usedNodes;
	}

	int Last() {
		return usedNodes - 1;
	}
};

struct PipeShard {
	// lowR is the diameter of bottom hole - smallest of all
	// highR is the diameter of top hole. Largest.
	LL lowR, highR;
	void Get(int source) {
		highR = GetLL(source);
		lowR = GetLL(source);
	}
	void Put(int target) {
		PutLL(target, highR);
		PutLL(target, lowR);
	}
};

struct ShardMapping {
	ShardMapping(int source) {
		Get(source);
	}
	ShardMapping(int b, int e, LL firstRealR, int pipeShard):
		b(b), e(e), firstRealR(firstRealR), pipeShard(pipeShard) {}
	int b, e;
	LL firstRealR;
	int pipeShard;
	void Put(int t) {
		PutInt(t, b);
		PutInt(t, e);
		PutLL(t, firstRealR);
		PutInt(t, pipeShard);
	}
	void Get(int s) {
		b = GetInt(s);
		e = GetInt(s);
		firstRealR = GetLL(s);
		pipeShard = GetInt(s);
	}
	bool operator<(const ShardMapping &s) const {
		return b < s.b;
	}
};

struct KRASolver {
	Sharding krShard, piShard;
	vector<PipeShard> pipes;
	int master_nr;

	KRASolver():
		krShard(NumberOfDiscs()),
		piShard(PipeHeight()),
		pipes(piShard.ShardCnt()),
		_nodeWorkLimit(-1) {}

	void solve() {
		// Set master to first node
		master_nr = 0; // WARNING: Master must be 0 at the start.
		if(piShard.ImUsed()) {
			int b, e;
			piShard.MyRange(b, e);
			LL first, minR;
			first = minR = HoleDiam(b);
			FOR(i, b+1, e-1) minR = min(HoleDiam(i), minR);
			PutLL(master_nr, first);
			PutLL(master_nr, minR);
			Send(master_nr);
		}

// TODO: DEBUG STOPPER
//		if (MyNodeId() == 0) {
//			bool stop = true;
//		    cout << "Find pid: " << getpid() << endl;
//			while(stop);
//
//		}

		if (Master()) {
			REP(x, piShard.ShardCnt()) {
				int source = Receive(-1);
				pipes[source].Get(source);
			}

			// If someone has a smaller bottom hole above in the pipe, then
			// all pipe radiuses will be no bigger than this hole. Top hole has
			// index 0.
			LL minAbove = pipes[0].lowR;
			FOR(i, 1, piShard.Last()) {
				PipeShard &s = pipes[i];
				s.highR = min(minAbove, s.highR);
				s.lowR = min(minAbove, s.lowR);
				minAbove = min(minAbove, s.lowR);
			}

			// Master does not send to himself
			// Master sends to 1
			// 1 to 2 3
			// 2 to 4 5
			// 3 to 6 7
			// etc

			if (NumberOfNodes() > 1) {
				SendPipes(1);
			}
		}

		if (NumberOfNodes() > 1 && !Master()) {
			int me = MyNodeId(), l = 2 * me, p = me * 2 + 1;
			int src = me / 2;

			Receive(src);
			REP(i, piShard.ShardCnt())
				pipes[i].Get(src);

			if (l < NumberOfNodes())
				SendPipes(l);
			if (p < NumberOfNodes())
				SendPipes(p);
		}

		if (krShard.ImUsed()) {
			// Everyone computes max disc size and sends this to the root.
			int b, e;
			krShard.MyRange(b, e);
			LL maxR = DiscDiam(b);
			FOR(i, b+1, e-1) maxR = max(maxR, DiscDiam(i));
			PutLL(master_nr, maxR);
			Send(master_nr);
		}

		if (Master()) {
			// Master computest the largest disc radius below each shard
			// and sends it back to the shard.
			// Disc nr 0 is the lowest, first falling, disc.
			vector<LL> maxDiscs(krShard.ShardCnt());
			REP(x, krShard.ShardCnt()) {
				int src = Receive(-1);
				maxDiscs[src] = GetLL(src);
			}
			FOR(x, 1, krShard.Last())
				maxDiscs[x] = max(maxDiscs[x], maxDiscs[x-1]);
			REP(nd, krShard.ShardCnt()) {
				LL m;
				if (nd == 0) m = -1;
				else m = maxDiscs[nd-1];
				PutLL(nd, m);
				Send(nd);
			}

		}

		if (krShard.ImUsed()) {
			generateDiscPipeMapping();

			// Here we will switch master to last node - least used one
			master_nr = NumberOfNodes()-1;

			PutInt(master_nr, (int)shMappings.size());
			REP(x, SIZE(shMappings)) {
				shMappings[x].Put(master_nr);
			}
			Send(master_nr);
		}
		else {
			// Here we will switch master to last node - least used one
			master_nr = NumberOfNodes()-1;
		}

		int expectedAnswersToMaster = 0;
		if (Master()) {
			// Receive all mappings, combine them into jobs, send out jobs.
			shMappings.clear();
			REP(x, krShard.ShardCnt()) {
				int source = Receive(-1);
				int len = GetInt(source);
				REP(y, len)
					shMappings.PB(ShardMapping(source));
			}
			sort(ALL(shMappings));
#ifdef DBG_CHECKS
			if (shMappings[0].b != 0)
				cerr << "ERROR: shMappings[0].b != 0" << endl;;
			if (shMappings.back().e != NumberOfDiscs())
				cerr << "ERROR: shMappings.back().e != NumberOfDiscs()" << endl;
			REP(x, SIZE(shMappings)-1) {
				if (shMappings[x].e != shMappings[x+1].b) {
					cerr << "ERROR: shMappings[x].e != shMappings[x+1].b" << endl;
					cerr << "Further entries ommited" << endl;
					break;
				}
			}
#endif
			// First merge
			vector<ShardMapping> m;
			FOREACH(it, shMappings) {
#ifdef DBG_CHECKS
				if (!m.empty() && m.back().pipeShard < it->pipeShard)
					cerr << "ERROR: !m.empty() && m.back().pipeShard < it->pipeShard" << endl;
#endif

				if (m.empty() || m.back().pipeShard != it->pipeShard)
					m.PB(*it);
				else
					m.back().e = it->e;
			}

			shMappings = m;
			m.clear();

			// Now split via size
			FOREACH(it, shMappings) {
				while((it->e - it->b) > nodeWorkLimit()) {
					int newE = it->b + nodeWorkLimit();
					m.PB(*it);
					m.back().e = newE;
					it->b = newE;
				}
				if ((it->e - it->b) > 0)
					m.PB(*it);
			}

			// Send jobs to all available workers, round robin.
			vector<vector<ShardMapping> > jobs(NumberOfNodes());
			int ndId = 0;
			FOREACH(it, m) {
				jobs[ndId].PB(*it);
				ndId = (ndId + 1) % NumberOfNodes();
			}

			REP(trg, NumberOfNodes()) {
				PutInt(trg, SIZE(jobs[trg]));
				if (SIZE(jobs[trg]) > 0) {
					FOREACH(it, jobs[trg])
						it->Put(trg);
					expectedAnswersToMaster += 1;
				}
				Send(trg);
			}
		}


		// Now each node calculates the slippage of discs on his slice of
		// pipe. This is guaranteed to be easy, beacause each disc in range
		// [b, e) stops in the given pipe (or above it, in case of the top
		// of the pipe).

		// Receive all jobs
		vector<ShardMapping> myJobs;
		Receive(master_nr);
		int jobCnt = GetInt(master_nr);
		REP(jobId, jobCnt)
			myJobs.PB(ShardMapping(master_nr)); // Receive from master

		int maxSlippage = -1;
		FOREACH(jobit, myJobs) {
			ShardMapping &m = *jobit;

			// I have some numbered discs and numbered pipes.
			// For each disc I must find the number of pipe at which it stops,
			// blocks and falls no further.
			// Then the slippage is the difference between the indices - reversed.

			// WARNING! Reverse order, beacause bottom of the pipe
			// has larger ids! We want to got bottom to top here.
			int piId, piBegin, piEnd;
			piShard.GetRange(m.pipeShard, piBegin, piEnd);

			vector<LL> piDiams(piEnd - piBegin);
			FOR(id, piBegin, piEnd-1)
				piDiams[id-piBegin] = HoleDiam(id);
			LL piDiam = pipes[m.pipeShard].highR;
			FOREACH(it, piDiams)
				piDiam = *it = min(*it, piDiam);

			piId = SIZE(piDiams)-1;
			int piHeight = PipeHeight();
			int piNr = piHeight - piEnd;
			piDiam = piDiams[piId];
//			cout <<"piNr initially:" <<piNr << endl;
//			cout <<"piBegin " << piBegin << " piEnd " << piEnd << endl;

			LL krDiam = m.firstRealR;
			FOR(krNr, m.b, m.e-1) {
				krDiam = max(krDiam, DiscDiam(krNr));

				while (piId > 0 && krDiam > piDiam) {
						piId -= 1;
						piDiam = piDiams[piId];
						piNr += 1;
//						cout <<"piNr goes to:" <<piNr << endl;
				}

				if (krDiam <= piDiam) {
					// Disc fits and this is the first spot it ever fit.
					if (piNr >= krNr) {
						maxSlippage = max(maxSlippage, piNr - krNr);
#ifdef DBG_FULL
						cout << "Slippage " << (piNr - krNr) << " piNr " << piNr << " krNr " << krNr << ", on node " << MyNodeId() << endl;
						cout << "piDiam " << piDiam << " krDiam " << krDiam << endl;
#endif
					}

// This is not a real ERROR. If slippage is negative then we simply have a
// disc whitch could fall lower but didn't because of other discs.
//
//#ifdef DBG_CHECKS
//					if (krNr > piNr) {
//						cerr << "ERROR: krNr > piNr (" << krNr << ' ' << piNr << ")" << endl;
//						cerr << "At node " << MyNodeId() << endl;
//					}
//#endif
				}
				else {
					if (m.pipeShard == 0) {
						// So the disc is bigger than the top of pipie.
						maxSlippage = (int)1.5E9; // 1.5E9
					}
					else {
#ifdef DBG_CHECKS
						cerr << "ERROR: m.pipeShard != 0 && krDiam > piDiam, at node " << MyNodeId() << endl;
#endif
					}
				}
			}
		}

		if (jobCnt) {
			PutInt(master_nr, maxSlippage);
			Send(master_nr);
		}

		if (Master()) {
			REP(x, expectedAnswersToMaster) {
				int src = Receive(-1);
				maxSlippage = max(maxSlippage, GetInt(src));
			}
			int d = PipeHeight() - NumberOfDiscs() - maxSlippage + 1;
			if (maxSlippage == (int)1.5E9) d = 0;
			if (d < 0) d = 0;
			cout << d << endl;
		}
	}

	int _nodeWorkLimit;
	int nodeWorkLimit() {
		if (_nodeWorkLimit == -1) {
			_nodeWorkLimit = NumberOfDiscs() / NumberOfNodes();
			_nodeWorkLimit = max(_nodeWorkLimit, 100);
		}
		return _nodeWorkLimit;
	}

	vector<ShardMapping> shMappings;

	void generateDiscPipeMapping() {
		// Disc shards receive max disc size below them (lower-indices)
		// and use this to max up all successive disc.
		Receive(master_nr);
		LL maxBelow = GetLL(master_nr);

		// Then for each disc they determine where it fits among the pipe
		// shards. Shards with lower numbers are wider.
		int b, e;
		krShard.MyRange(b, e);

		int piShr = piShard.Last(); // Stop krążka gwarantowany przez poz.

		FOR(i, b, e-1) {
			LL discR = maxBelow = max(DiscDiam(i), maxBelow);

			// Advance until it enters the pipe or we are at the top of pipe.
			while(piShr > 0 && pipes[piShr].highR < discR) {
				// Disc does not enter this pipe, yet this is not the top one.
				piShr -= 1;
			}
			// Either this is the top pipe, so disc will lie on top of it
			// or it can enter from the top, but not fall from bottom.

			// disc will block in shard piShr
			addToMappings(i, piShr, discR);
		}
	}

	void SendPipes(int trg) {
		REP(i, piShard.ShardCnt())
			pipes[i].Put(trg);
		Send(trg);
	}

	void addToMappings(int i, int piShr, LL discR) {
		if (shMappings.empty()) {
			shMappings.PB(ShardMapping(i, i+1, discR, piShr));
		}
		else {
			ShardMapping &m = shMappings.back();
			if (m.pipeShard == piShr) {
#ifdef DBG_CHECKS
				if (m.e != i) cerr << "ERROR: m.e != i" << endl;
#endif
				m.e += 1;
			}
			else {
				shMappings.PB(ShardMapping(i, i+1, discR, piShr));
			}
		}
	}

	long long int HoleDiam(long long int i) {
		return HoleDiameter(i+1);
	}

	long long int DiscDiam(long long int j) {
		return DiscDiameter(j+1);
	}

	bool Master() {
		return MyNodeId() == master_nr;
	}

};


int main(int argc, char *argv[]) {
#define deb(x) cout << #x << " = " << x << endl;
//	if (argc == 2 && strcmp(argv[1], "debug") == 0 ) {
//		//        printf("== [RUNNING IN DEBUG MODE]==\n\n");
//		char test_file_path[] = "/home/horban/workspace/Zadanka/in.txt";
//		freopen(test_file_path, "r", stdin);
//	}
    // TODO: UWAGA NA TO PRZED WYSLANIEM
//	std::ios_base::sync_with_stdio(0);
	KRASolver sol;
	sol.solve();


    return 0;
}