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
539
540
541
542
543
544
545
546
547
548
#ifndef MW_HEADER
#define MW_HEADER
#include <bits/stdc++.h>
#include "message.h"
using namespace std;

#define FOR(i,a,b) for (LL i = (a); i < (b); ++i)
#define FORD(i,b,a) for (LL i = (LL)(b)-1; i >= (a); --i)
#define REP(i,N) FOR(i,0,N)
#define FOREACH(i,x) for (__typeof((x).begin()) i=(x).begin(); i!=(x).end(); ++i)
#define st first
#define nd second
#define pb push_back

typedef pair<int, int> PII;
typedef long long LL;
typedef unsigned long long ULL;
#endif

LL NODES = NumberOfNodes(), ME = MyNodeId();
LL __N, START, END, NEXT, PREV;
LL get_start(int node) { return __N/NODES * node + min(__N%NODES, (LL)node); }
LL get_end(int node) { return get_start(node+1); }
/** Every node has at least factor items to process */
void reduce_nodes(LL N, int factor = 1) {
  NODES = min(NODES, max(N/factor, 1LL)); if (ME >= NODES) exit(0);
  NEXT = (ME + 1)%NODES, PREV=(ME+NODES-1)%NODES;
  __N = N;  START = get_start(ME), END = get_end(ME);
}

template <typename Container> struct is_container : false_type { };
template <typename... Ts> struct is_container<list<Ts...> > : true_type { };
template <typename... Ts> struct is_container<vector<Ts...> > : true_type { };
template <typename... Ts> struct is_container<deque<Ts...> > : true_type { };

// template <typename... Ts> struct is_container<set<Ts...> > : true_type { };
// template <typename... Ts> struct is_container<map<Ts...> > : true_type { };
template <typename Container> struct is_pair : false_type { };
template <typename... Ts> struct is_pair<pair<Ts...>> : true_type { };
template <typename Container> struct is_triple : false_type { };
template <typename T1, typename T2, typename T3> struct is_triple<tuple<T1,T2,T3>> : true_type { };

template<typename T> void Put(int target, typename enable_if<!is_class<T>::value, const T&>::type value) { T::not_implemented; }
template<typename T> void Put(int target, typename enable_if<is_container<T>::value, const T&>::type vec);
template<> void Put<bool>(int target, const bool& value) { PutChar(target, value); }
template<> void Put<char>(int target, const char& value) { PutChar(target, value); }
template<> void Put<int>(int target, const int& value) { PutInt(target, value); }
template<> void Put<unsigned int>(int target, const unsigned int& value) { PutInt(target, value); }
template<> void Put<long long>(int target, const long long& value) { PutLL(target, value); }
template<> void Put<unsigned long long>(int target, const unsigned long long& value) { PutLL(target, value); }
// template<typename T> void Put(int target, typename enable_if<is_class<T>::value && !is_container<T>::value && !is_pair<T>::value, const T&>::type value){
//   char data[sizeof(T)]; memcpy(data, &value, sizeof(T));
//   REP(i, (int)sizeof(T)) PutChar(target, data[i]);
// }
template<typename T> void Put(int target, typename enable_if<is_pair<T>::value, const T&>::type pair) {
  Put<typename T::first_type>(target, pair.first);
  Put<typename T::second_type>(target, pair.second);
}
template<typename T> void Put(int target, typename enable_if<is_triple<T>::value, const T&>::type triple) {
  Put<typename tuple_element<0, T>::type>(target, get<0>(triple));
  Put<typename tuple_element<1, T>::type>(target, get<1>(triple));
  Put<typename tuple_element<2, T>::type>(target, get<2>(triple));
}
const int MAX_MESSAGE_SIZE = 62000;
const int PARTS = -1;
template<typename T> void Put(int target, typename enable_if<is_container<T>::value, const T&>::type vec) {
  int data_size = vec.size() * sizeof(typename T::value_type);

  int parts = 1 + data_size / MAX_MESSAGE_SIZE;
  int part_size = (vec.size() + parts-1) / parts;

  Put<int>(target, parts);
  for (int p = 0; p < parts; ++p) {
    int start = p*part_size;
    int end = min((int)vec.size(), (p+1)*part_size);
    Put<int>(target, end-start);
    FOR(i, start, end) {
      Put<typename T::value_type>(target, vec[i]);
    }
    if (p < parts-1) {
      Send(target);
    }
  }
}

template<typename T> typename enable_if<!is_class<T>::value, T>::type Get(int source) { T::not_implemented; }
template<typename T> typename enable_if<is_container<T>::value, T>::type Get(int source);
template<> bool Get<bool>(int source) { return GetChar(source); }
template<> char Get<char>(int source) { return GetChar(source); }
template<> int Get<int>(int source) { return GetInt(source); }
template<> unsigned int Get<unsigned int>(int source) { return GetInt(source); }
template<> long long Get<long long>(int source) { return GetLL(source); }
template<> unsigned long long Get<unsigned long long>(int source) { return GetLL(source); }
// template<typename T> typename enable_if<is_class<T>::value && !is_container<T>::value && !is_pair<T>::value, T>::type Get(int source) {
//   char data[sizeof(T)]; REP(i, (int)sizeof(T)) data[i] = GetChar(source);
//   T value; memcpy(&value, data, sizeof(T));
//   return value;
// }
template<typename T> typename enable_if<is_pair<T>::value, T>::type Get(int source) {
  auto f = Get<typename T::first_type>(source);
  auto s = Get<typename T::second_type>(source);
  return T(f, s);
}
template<typename T> typename enable_if<is_triple<T>::value, T>::type Get(int source) {
  auto f = Get<typename tuple_element<0, T>::type>(source);
  auto s = Get<typename tuple_element<1, T>::type>(source);
  auto t = Get<typename tuple_element<2, T>::type>(source);
  return T(f, s, t);
}
template<typename T> typename enable_if<is_container<T>::value, T>::type Get(int source) {
  int parts = GetInt(source);

  vector<typename T::value_type> result;
  REP(p, parts) {
    if (p > 0) Receive(source);

    int size = GetInt(source);
    REP(i,size) result.push_back(Get<typename T::value_type>(source));
  }

  return T(result.begin(), result.end());
}

template<typename T> void Broadcast(int source, T& value) {
  if (ME == source) REP(i,NODES) { Put<T>(i, value); Send(i); }
  Receive(source); value = Get<T>(source);
}

template<typename T> void BroadcastTree(int source, T& value) {
  int relative = (ME - source + NODES) % NODES;
  if (relative) {
    int from = (source + (relative-1) / 2) % NODES;
    Receive(from); value = Get<T>(from);
  }
  FOR(i,1,3) if (2*relative + i < NODES) {
    int to = ((source + 2*relative + i) % NODES);
    Put<T>(to, value); Send(to);
  }
}

template<typename T, typename Fn> void Accumulate(int target, const T& value, Fn fn) {
  Put<T>(target, value); Send(target);
  if (ME == target) REP(i, NODES) { Receive(i); fn(Get<T>(i)); }
}

/** ~5ms for adding ints */
template<typename T, typename Fn> T AccumulateTree(int target, T value, Fn fn) {
  int relative = (ME - target + NODES) % NODES;
  for (int b = 1; b < NODES; b <<= 1) {
    if (relative&b) {
      int to = (target + relative - b + NODES) % NODES;
      Put<T>(to, value); Send(to); break;
    } else if (relative + b < NODES) {
      int from = (target + relative + b) % NODES;
      Receive(from); value = fn(value, Get<T>(from));
    }
  }

  return value;
}

template<typename T, typename Compute, typename Acc> T AccumulateValues(int target, Compute fn, Acc acc) {
  T result = fn(START);
  FOR(i,START+1,END) result = acc(result, fn(i));
  return AccumulateTree(target, result, acc);
}

template<typename T, typename Compute> vector<T> AccumulateVector(int target, Compute fn) {
  vector<T> local; FOR(i,START, END) local.pb(fn(i));
  vector<T> acc;
  Accumulate(target, local, [&](const vector<T>& vec) {acc.insert(acc.end(), vec.begin(), vec.end());});
  return acc;
}

template<typename T> vector<T> Collect(int target, const T& value) {
  vector<T> acc;
  Accumulate(target, value, [&](const T& val) { acc.pb(val); });
  return acc;
}
// ^^^ CUT HERE ^^^

#include "skup.h"

typedef pair<LL, LL> Token;
typedef pair<Token, deque<int>> TokenMove;

typedef pair<Token, vector<int>> HelpRequest;
typedef vector<int> Help;

Token empty_token() {
  return Token(0, 0);
}

bool token_has_all(const Token& token) {
  return
    token.st == (1LL<<(min(50LL, NODES))) - 1
    && token.nd == (1LL<<(max(0LL, NODES-50))) - 1;
}

void token_add(Token& summing, const Token& added) {
  summing.st |= added.st;
  summing.nd |= added.nd;
}

void token_set(Token& token, int id) {
  if (id < 50) token.st |= (1LL<<id);
  else token.nd |= (1LL<<(id-50));
}

bool token_has(const Token& token, int id) {
  if (id < 50) return token.st & (1LL<<id);
  else return token.nd & (1LL<<(id-50));
}

// In the dark
const int I_CAN_HEAR_YOU = 1;
const int DFS = 2;
const int GIVE_DATA = 3;

// Data
const int DFS_RESULT = 8;
const int TOKEN = 9;
const int DATA = 10;
const int YOURE_NOT_MY_FATHER = 11;
const int NEED_HELP = 12;
const int HELP_RESPONSE = 13;

#define dprintf(...) printf(__VA_ARGS__); fflush(stdout);

void on_outbound(int v);
void on_token_received(Token token);

void start_dfs();
void on_dfs_request(int source);
void on_dfs_response(Token response);
void on_dfs_finish();

void on_help_request(HelpRequest _help_request);
void check_outbound_for_token_move(int v);
void on_help_received(TokenMove move);
void move_token(TokenMove move);
void on_token_move_received(int source, TokenMove move);

void on_data_request(int source);
void on_data_received(vector<int> _data);
void on_data_completed();

vector<int> inbound;
set<int> outbound;
int parent = ME;
set<int> children;

Token token = {0, 0};
bool I_am_root = false;
bool I_started_dfs = false;
vector<int> data;
int needed_answers_for_dfs = 0;
set<int> waiting_for_data_from;

void on_outbound(int v) {
  // dprintf("%d can hear me :)\n", v);
  outbound.insert(v);
  check_outbound_for_token_move(v);
}

void on_token_received(Token _token) {
  if (parent != ME) {
    // dprintf("%d is not my parent anymore\n", parent);
    PutInt(parent, YOURE_NOT_MY_FATHER);
    Send(parent);
  }

  parent = ME;
  token = _token;
  I_am_root = true;
  start_dfs();
}

void start_dfs() {
  // dprintf("Starting DFS...\n");
  token_set(token, ME);
  for (int n: inbound) if (!token_has(token, n)) {
    PutInt(n, DFS);
    Send(n);
    ++needed_answers_for_dfs;
  }
  I_started_dfs = true;
  if (!needed_answers_for_dfs) {
    on_dfs_finish();
  }
}

void on_dfs_request(int source) {
  if (I_started_dfs) {
    // dprintf("%d requested DFS, but I already have a parent.\n", source);
    PutInt(source, DFS_RESULT);
    Put<Token>(source, empty_token());
    Send(source);
    return;
  }

  // dprintf("Setting parent to %d\n", source);
  parent = source;
  start_dfs();
}

void on_dfs_response(int source, Token response) {
  // dprintf("Got DFS response from %d\n", source);
  if (response != empty_token()) {
    // dprintf("Setting %d as my child\n", source);
    children.insert(source);
  }
  token_add(token, response);
  --needed_answers_for_dfs;
  // dprintf("Still need %d DFS responses\n", needed_answers_for_dfs);
  if (!needed_answers_for_dfs) {
    on_dfs_finish();
  }
}

void on_dfs_finish() {
  // dprintf("Finishing DFS (%lld)\n", token.st);
  if (!I_am_root) {
    // dprintf("Sending my DFS data to %d\n", parent);
    PutInt(parent, DFS_RESULT);
    Put<Token>(parent, token);
    Send(parent);
    return;
  }

  if (token_has_all(token)) {
    // dprintf("I will finish this.\n"); fflush(stdout);
    on_data_request(ME);
  } else {
    // dprintf("I need to get rid of token\n");
    on_help_request(HelpRequest(token, vector<int>()));
  }
}

HelpRequest help_request;
bool I_got_asked_for_help = false;
bool I_helped = false;

void on_help_request(HelpRequest _help_request) {
  if (I_got_asked_for_help || I_helped) {
    // dprintf("Ignoring help request\n");
    return;
  }
  // dprintf("Processing help request\n");

  I_got_asked_for_help = true;
  help_request = _help_request;
  help_request.nd.pb(ME);

  for (int v: outbound) {
    check_outbound_for_token_move(v);
  }
}

void check_outbound_for_token_move(int v) {
  if (!I_got_asked_for_help || I_helped) {
    // dprintf("Not processing %d for help request\n", v);
    return;
  }

  if (!token_has(help_request.st, v)) {
    // dprintf("Found help from %d!\n", v);
    deque<int> move(help_request.nd.begin(), help_request.nd.end());
    move.push_back(v);
    on_help_received(TokenMove(help_request.st, move));
  } else {
    // dprintf("Extending help request to %d\n", v);
    PutInt(v, NEED_HELP);
    Put<HelpRequest>(v, help_request);
    Send(v);
  }
}

void on_help_received(TokenMove move) {
  if (I_helped) {
    // dprintf("Got help response, but I already helped\n");
    return;
  }

  I_helped = true;
  if (move.nd[0] != ME && parent != ME) {
    PutInt(parent, HELP_RESPONSE);
    Put<TokenMove>(parent, move);
    Send(parent);
  } else if (move.nd[0] == ME && I_am_root) {
    move.nd.pop_front();
    move_token(move);
  }
}

void move_token(TokenMove move) {
  // dprintf("Moving token to %d...\n", move.nd[0]);

  I_am_root = false;
  if (ME != parent) {
    // dprintf("%d is not my father\n", parent);
    PutInt(parent, YOURE_NOT_MY_FATHER);
    Send(parent);
  }
  parent = move.nd[0];

  PutInt(move.nd[0], TOKEN);
  Put<TokenMove>(move.nd[0], move);
  Send(move.nd[0]);
}

void on_token_move_received(int source, TokenMove move) {
  // dprintf("Received token move request from %d\n", source);
  children.insert(source);
  move.nd.pop_front();
  if (move.nd.empty()) {
    on_token_received(move.st);
  } else {
    move_token(move);
  }
}

void on_data_request(int source) {
  I_helped = true;

  if (source != parent) {
    return;
  }

  for (int n: children) {
    // dprintf("Asking %d for data\n", n); fflush(stdout);
    PutInt(n, GIVE_DATA);
    Send(n);
    waiting_for_data_from.insert(n);
  }

  if (waiting_for_data_from.empty()) {
    on_data_completed();
  }
}

void on_data_received(int source, vector<int> _data) {
  data.insert(data.end(), _data.begin(), _data.end());
  waiting_for_data_from.erase(source);
  if (waiting_for_data_from.empty()) {
    on_data_completed();
  }
}

void on_data_completed() {
  if (I_am_root) {
    sort(data.rbegin(), data.rend());
    LL result = 0;
    REP(i, data.size()) {
      result += (i+1) * data[i];
    }
    printf("%lld\n", result);
  } else {
    // dprintf("I am sending data to %d: ", parent); for(int k: data) // dprintf("%d ", k); // dprintf("\n"); fflush(stdout);
    PutInt(parent, DATA);
    Put<vector<int>>(parent, data);
    Send(parent);
  }

  exit(0);
}

int main() {
  // ios_base::sync_with_stdio(0);

  LL companies = NumberOfCompanies();
  REP(i,companies) {
    data.pb(GetShareCost(i));
  }

  REP(n, NODES) if (n != ME) {
    PutInt(n, 1);
    Send(n);
  }

  REP (n,NODES) if (n != ME) {
    Receive(n);
    int msg = GetInt(n);
    if (msg) {
      // dprintf("I can hear %lld\n", n); fflush(stdout);
      inbound.pb(n);
      PutInt(n, I_CAN_HEAR_YOU);

      Send(n);
    }
  }

  token_set(token, ME);
  if (ME == 0) {
    on_token_received(token);
  }

  while (true) {
    int source = Receive(-1);
    int type = GetInt(source);

    if (type == 0) {
      if (outbound.find(source) == outbound.end()) {
        type = I_CAN_HEAR_YOU;
      } else if (source == parent) {
        type = GIVE_DATA;
      } else {
        type = DFS;
      }
    }

    // // dprintf("Message type: %d\n", type);

    if (type == I_CAN_HEAR_YOU) {
        on_outbound(source);
    } else if (type == DFS) {
        on_dfs_request(source);
    } else if (type == DFS_RESULT) {
        Token received_token = Get<Token>(source);
        on_dfs_response(source, received_token);
    } else if (type == TOKEN) {
        TokenMove token_move = Get<TokenMove>(source);
        on_token_move_received(source, token_move);
    } else if (type == YOURE_NOT_MY_FATHER) {
        // dprintf("%d is not my child anymore\n", source);
        children.erase(source);
        if (waiting_for_data_from.find(source) != waiting_for_data_from.end()) {
          waiting_for_data_from.erase(source);
          if (waiting_for_data_from.empty()) {
            on_data_completed();
          }
        }
    } else if (type == GIVE_DATA) {
        on_data_request(source);
    } else if (type == DATA) {
        vector<int> rec = Get<vector<int>>(source);
        on_data_received(source, rec);
    } else if (type == NEED_HELP) {
      HelpRequest help_request = Get<HelpRequest>(source);
      on_help_request(help_request);
    } else if (type == HELP_RESPONSE) {
      TokenMove resp = Get<TokenMove>(source);
      on_help_received(resp);
    } else {
      throw type;
    }
  }
}