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
// clang-format off
// It's hashing time! https://youtu.be/bS5P_LAqiVg?t=613
// hash of a_0, a_1, ..., a_n = a_0 + a_1 * Prime + a_2 * Prime^2 + ... + a_n * Prime^n
// clang-format on

#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#include "message.h"
#include "poszukiwania.h"

using namespace std;

#define COLOR_BLACK "\x1b[30m"
#define COLOR_RED "\x1b[31m"
#define COLOR_GREEN "\x1b[32m"
#define COLOR_YELLOW "\x1b[33m"
#define COLOR_BLUE "\x1b[34m"
#define COLOR_MAGENTA "\x1b[35m"
#define COLOR_CYAN "\x1b[36m"
#define COLOR_WHITE "\x1b[37m"
#define COLOR_RESET "\x1b[0m"

#define COLOR_BOLDBLACK "\033[1m\033[30m"
#define COLOR_BOLDRED "\033[1m\033[31m"
#define COLOR_BOLDGREEN "\033[1m\033[32m"
#define COLOR_BOLDYELLOW "\033[1m\033[33m"
#define COLOR_BOLDBLUE "\033[1m\033[34m"
#define COLOR_BOLDMAGENTA "\033[1m\033[35m"
#define COLOR_BOLDCYAN "\033[1m\033[36m"
#define COLOR_BOLDWHITE "\033[1m\033[37m"

const std::vector<const char*> colors{
    COLOR_RED,        COLOR_GREEN,    COLOR_YELLOW,      COLOR_BLUE,
    COLOR_MAGENTA,    COLOR_CYAN,     COLOR_BOLDRED,     COLOR_BOLDGREEN,
    COLOR_BOLDYELLOW, COLOR_BOLDBLUE, COLOR_BOLDMAGENTA, COLOR_BOLDCYAN};

#define NDEBUG

#ifndef NDEBUG
#include <fstream>
#include <cstring>
struct MemChecker {
  ~MemChecker() {
    std::ifstream infile("/proc/self/status");
    std::string line;
    while (std::getline(infile, line)) {
      if (line.compare(0, 6, "VmPeak") == 0) {
        int rv = 0;
        for (int i = 0; i < line.size(); ++i) {
          if (line[i] >= '0' && line[i] <= '9') {
            rv = 10 * rv + (line[i] - '0');
          }
        }
        std::cerr << "memory: " << rv << " kB" << std::endl;
        return;
      }
    }
    std::cerr << "memory stats not found" << std::endl;
  }
} __mem_checker;

#define cdebug \
  cerr << colors[MyNodeId() % colors.size()] << "node" << COLOR_RESET << " "

#else

class DebugStream {};
template <typename T>
DebugStream& operator<<(DebugStream& s, T) {
  return s;
}

DebugStream cdebug;

#endif

typedef long long LL;
constexpr LL kPrime = 1100000227;
constexpr LL kPrimeMod = 1600002223;
constexpr LL kInitHash = 1;
int P;    // number of instances
int N;    // text length
int M;    // pattern length
int CS;   // chunk length (size)
int Pid;  // current instance id

LL Occurences;  // occurences count

int BufSizes[101];
int TotalSent[101];
void _PutLL(int target, long long x) {
  //  BufSizes[target] += 8;
  //  TotalSent[target] += 8;
  PutLL(target, x);
}
void _PutInt(int target, int x) {
  //  BufSizes[target] += 4;
  //  TotalSent[target] += 4;
  PutInt(target, x);
}
void _PutChar(int target, char x) {
  //  BufSizes[target] += 1;
  //  TotalSent[target] += 1;
  PutChar(target, x);
}
void _Send(int target) {
  //  std::cerr << "sending " << BufSizes[target] << " bytes\n";
  //  BufSizes[target] = 0;
  Send(target);
}

// indexes start at 0
LL Text(int i) {
  assert(i >= 0 && i < N);
  return i < SeqLength() ? SeqAt(i + 1) : 1000000010;
}
LL Pattern(int i) {
  assert(i >= 0 && i < M);
  return SignalAt(i + 1);
}
LL TextBegin() { return CS * Pid; }
LL TextEnd() { return CS * (Pid + 1); }

vector<LL> ChunkHashes;
LL PatternPrefixHash;  // hash of the prefix of maximum len divisible by CS

LL hashsh(const vector<LL>& vec) {
  LL hash = 0;
  LL p = kInitHash;
  for (LL i : vec) {
    hash = (hash + p * i) % kPrimeMod;
    p = p * kPrime % kPrimeMod;
  }
  return hash;
}

// Init.
void MyInit() {
  N = SeqLength();
  M = SignalLength();
  P = min(NumberOfNodes(), N / 3);
  Pid = MyNodeId();

  if (Pid >= P) {
    exit(0);
  }

  if (N % P) {
    N += P - N % P;
  }
  CS = N / P;
  ChunkHashes.resize(P);

  for (int i = CS * Pid; i < CS * (Pid + 1); ++i) {
    cdebug << "text[" << i << "] " << Text(i) << "\n";
  }

  if (Pid == 0) {
    for (int i = 0; i < M; ++i) {
      cdebug << "pattern[" << i << "] " << Pattern(i) << "\n";
    }
  }
}

// Compute chunk hashes and send them everyone (and receive from everyone).
void ComputeChunkHashes() {
  LL my_hash = 0;
  LL p = kInitHash;
  for (LL i = TextBegin(); i < TextEnd(); ++i) {
    my_hash = (my_hash + p * Text(i)) % kPrimeMod;
    p = p * kPrime % kPrimeMod;
  }
  for (int pid = 0; pid < P; ++pid) {
    if (pid == Pid) {
      continue;
    }
    _PutLL(pid, my_hash);
    _Send(pid);
  }
  ChunkHashes[Pid] = my_hash;
  for (int pid = 0; pid < P; ++pid) {
    if (pid == Pid) {
      continue;
    }
    Receive(pid);
    ChunkHashes[pid] = GetLL(pid);
  }

  if (Pid == 0) {
    for (int i = 0; i < P; ++i) {
      cdebug << "hash " << i << " = " << ChunkHashes[i] << "\n";
    }
  }
}

// a ^ x mod kPrimeMod
LL Exp(LL a, LL x) {
  LL res = 1;
  while (x > 0) {
    if (x & 1) {
      res = res * a % kPrimeMod;
    }
    a = a * a % kPrimeMod;
    x >>= 1;
  }
  return res;
}

// Compute PatternPrefixHash.
void ComputePatternPrefixHash() {
  if (M < CS) {
    return;
  }
  LL prefix_len = M - M % CS;
  LL my_part_start = prefix_len * Pid / P;
  LL my_part_end = prefix_len * (Pid + 1) / P;
  LL my_part_hash = 0;
  LL p = kInitHash;
  for (LL i = my_part_start; i < my_part_end; ++i) {
    my_part_hash = (my_part_hash + p * Pattern(i)) % kPrimeMod;
    p = p * kPrime % kPrimeMod;
  }

  PatternPrefixHash = 0;
  cdebug << " MY pattern prefix hash part " << my_part_start << ".."
         << my_part_end << " : " << my_part_hash << "\n";
  // Send it to the first instance.
  _PutLL(0, my_part_hash);
  _Send(0);
  if (Pid == 0) {
    // Merge it.
    for (int pid = 0; pid < P; ++pid) {
      Receive(pid);
      LL received = GetLL(pid);
      PatternPrefixHash += received * Exp(kPrime, prefix_len * pid / P);
      PatternPrefixHash %= kPrimeMod;
    }
    // Send it back to all other instances.
    for (int i = 1; i < P; ++i) {
      _PutLL(i, PatternPrefixHash);
      _Send(i);
    }
    cdebug << "pattern prefix hash " << PatternPrefixHash << "\n";
  } else {
    // Receive.
    Receive(0);
    PatternPrefixHash = GetLL(0);
  }
}

LL ArrTail(int pos) {
  if (pos < CS) {
    return Text(Pid * CS + pos);
  } else if (pos == CS) {
    return 1000000020;
  } else {
    return Pattern(max(0, M - CS) + pos - CS - 1);
  }
}

// One needs to send to at most to others. <how many back, how many bits>
pair<pair<int, int>, pair<int, int>> _CalcSendTo() {
  if (M == 1) {
    return make_pair(make_pair(-1, -1), make_pair(-1, -1));
  }
  if (M <= CS + 1) {
    return make_pair(make_pair(1, M - 1), make_pair(-1, -1));
  }
  if ((M - 1) % CS == 0) {
    return make_pair(make_pair(M / CS + 1, CS), make_pair(-1, -1));
  }
  int first_sent = (M - 2) / CS + 1;
  int bits_sent = (M - 2) % CS + 1;
  return make_pair(make_pair(first_sent, bits_sent),
                   make_pair(first_sent - 1, CS - bits_sent));
}

pair<pair<int, int>, pair<int, int>> CalcSendTo() {
  auto rv = _CalcSendTo();
  if (rv.second.second == -1) {
    cdebug << "send/receive: " << rv.first.first << " " << rv.first.second
           << "\n";
  } else {
    cdebug << "send/receive: " << rv.first.first << " " << rv.first.second
           << " " << rv.second.first << " " << rv.second.second << "\n";
  }
  return rv;
}

// 250000 bytes at once at most
const int kBytesAtOnce = 250000;
void SendBits(int target, int start, int end, const vector<bool>& bits) {
  if (target < 0 || target >= P) {
    return;
  }
  cdebug << "SendBits to " << target << " " << start << ".." << end << "\n";
  //  _PutInt(target, end - start);

  while (start < end) {
    for (int i = 0; i < kBytesAtOnce && start < end; ++i) {
      char x = 0;
      int j = 0;
      for (j = 0; j < 8 && start < end; ++j) {
        x <<= 1;
        x |= (int)bits[start];
        ++start;
      }
      x <<= (8 - j);
      cdebug << " sending 0x" << std::hex << (uint)x << std::dec << "\n";
      _PutChar(target, x);
    }
    _Send(target);
  }
  cdebug << "done sending\n";
}

void ReceiveBits(int target, int start, int end, vector<bool>& bits) {
  if (target < 0 || target >= P) {
    return;
  }
  cdebug << "ReceiveBits from " << target << " " << start << ".." << end
         << "\n";
  //  if (len != end - start) {
  //    cdebug << "len " << len << " start " << start << " end " << end << " ("
  //           << end - start << ")\n";
  //    assert(0);
  //  }

  while (start < end) {
    Receive(target);
    for (int i = 0; i < kBytesAtOnce && start < end; ++i) {
      char x = GetChar(target);
      cdebug << " received 0x" << std::hex << (uint)x << std::dec << "\n";
      for (int j = 7; j >= 0 && start < end; --j) {
        bits[start] = (x & (1 << j)) > 0;
        ++start;
      }
    }
  }
  cdebug << "done receiving\n";
}

// Sent positions where the pattern can end (checking only data in this chunk).
void SendBackMyStats() {
  // Pref-suf array for <chunk>#<pattern tail> (don't keep the second part of
  // the array T).
  // 2 * 10 ^ 9 / 100 * 4 B = 80 MB. Phew!
  // indexed from 1, sorry.
  vector<int> T(CS + 2);  // for Chunk
  int k = T[0] = -1;
  for (int i = 0; i < CS; ++i) {
    while (k >= 0 && ArrTail(k) != ArrTail(i)) {
      k = T[k];
    }
    ++k;
    T[i + 1] = k;
    //    cdebug << "k at i + 1 = " << i + 1 << " = " << k << "\n";
  }
  // No match for #.
  k = 0;
  // Let's try'em patterns.
  for (int i = 0; i < min(M, CS); ++i) {
    while (k >= 0 && ArrTail(k) != ArrTail(CS + 1 + i)) {
      k = T[k];
    }
    ++k;
    //    cdebug << " __ k at i + 1 = " << i + 1 << " = " << k << "\n";
  }
  // Iterate over pref-sufs.
  cdebug << "final k: " << k << "\n";
  // < 3 MB
  // Where a match can end?
  vector<bool> matches(CS);
  while (k > 0) {
    cdebug << "output : " << k - 1 << "\n";
    matches[k - 1] = true;
    k = T[k];
  }
  for (int i = 0; i < CS; ++i) {
    cdebug << " sending matches: " << matches[i] << "\n";
  }
  // figure out where and what data to send and do it
  auto send_to = CalcSendTo();
  if (send_to.first.second != -1) {
    SendBits(Pid - send_to.first.first, 0, send_to.first.second, matches);
    if (send_to.second.second != -1) {
      SendBits(Pid - send_to.second.first, send_to.first.second, CS, matches);
    }
  }
}

LL ArrHead(int pos) {
  if (pos < M) {
    return Pattern(pos);
  } else if (pos == M) {
    return 1000000030;
  } else {
    return Text(Pid * CS + pos - CS - 1);
  }
}

// iterate over the positions in this chunk and count pattern occurences
void CalculateResultForChunk() {
  if ((P - Pid) * CS < M) {
    cdebug << "nothing fits\n";
    return;  // nothing fits
  }
  vector<bool> matches(CS);
  // receive the sent data.
  auto receive_from = CalcSendTo();
  if (receive_from.first.second != -1) {
    ReceiveBits(Pid + receive_from.first.first, CS - receive_from.first.second,
                CS, matches);
    if (receive_from.second.second != -1) {
      ReceiveBits(Pid + receive_from.second.first, 0,
                  CS - receive_from.first.second, matches);
    }
  }

  for (int i = 0; i < CS; ++i) {
    cdebug << " rec matches: " << matches[i] << "\n";
  }

  if (M < CS) {
    // 1. M < CS
    // We won't fit any full chunks hashes - KMP this shit.
    // Pref-suf array for <pattern>#<chunk> (don't keep the second part of
    // the array T).
    // indexed from 1, as above.
    // WE'RE LOOKING FOR WHOLE MATCHES TOO
    vector<int> T(M + 2);  // for pattern
    int k = T[0] = -1;
    for (int i = 0; i < M; ++i) {
      while (k >= 0 && ArrHead(k) != ArrHead(i)) {
        k = T[k];
      }
      ++k;
      T[i + 1] = k;
      cdebug << "k at i + 1 = " << i + 1 << " = " << k << "\n";
    }
    // No match for #.
    k = 0;
    // Let's try'em patterns.
    for (int i = 0; i < CS; ++i) {
      while (k >= 0 && ArrHead(k) != ArrHead(CS + 1 + i)) {
        k = T[k];
      }
      ++k;
      if (k == M) {
        cdebug << "---------OCC k == M\n";
        ++Occurences;
      }
      cdebug << " __ k at i + 1 = " << i + 1 << " = " << k << "\n";
    }

    cdebug << "final k: " << k << "\n";

    while (k > 0) {
      cdebug << " matches : " << k - 1 << " " << matches[k - 1] << "\n";
      if (matches[CS - k]) {
        cdebug << " ---------OCC matches[CS - k]\n";
        ++Occurences;
      }
      k = T[k];
    }

    return;
  }

  // 2. M >= CS.
  // Get the hash of the chunks that fit in the pattern and move it move it!
  LL hash = 0;
  for (int i = 0; CS * (i + 1) <= M; ++i) {
    hash = (hash + ChunkHashes[Pid + i] * Exp(kPrime, CS * i)) % kPrimeMod;
    cdebug << "added chunk " << Pid + i << " to hash " << hash << "\n";
  }
  LL p = 1;
  for (int i = 0; i < CS; ++i) {
    LL moved_pattern_hash = PatternPrefixHash * p % kPrimeMod;
    cdebug << "hash at " << i << " " << hash << " PatternHash "
           << moved_pattern_hash << " orig " << PatternPrefixHash << "\n";
    if (moved_pattern_hash == hash && (matches[i] || (i == 0 && M % CS == 0))) {
      cdebug << " ---------OCC match at " << i << "\n";
      ++Occurences;
    }
    // chop the first hash and the last from PatternPrefixHash and move hash
    // (multiply the multiplier by Prime)
    hash -= p * Text(CS * Pid + i) % kPrimeMod;
    cdebug << "  hash tmp 1 " << hash << " (Text " << Text(CS * Pid + i)
           << ")\n";
    hash = (hash + kPrimeMod) % kPrimeMod;
    cdebug << "  hash tmp 2 " << hash << "\n";
    p = p * kPrime % kPrimeMod;
    PatternPrefixHash -= Pattern(M - M % CS - i - 1) *
                         Exp(kPrime, M - M % CS - i - 1) % kPrimeMod;
    cdebug << "  pattern hash tmp 1 " << PatternPrefixHash << " ("
           << Pattern(M - M % CS - i - 1) << " "
           << Pattern(M - M % CS - i - 1) * Exp(kPrime, M - M % CS - i - 1) %
                  kPrimeMod
           << ")\n";
    PatternPrefixHash = (PatternPrefixHash + kPrimeMod) % kPrimeMod;
    cdebug << "  pattern hash tmp 2 " << PatternPrefixHash << "\n";
  }
}

void Final() {
  if (Pid == 0) {
    for (int pid = 1; pid < P; ++pid) {
      Receive(pid);
      Occurences += GetLL(pid);
    }
    cout << Occurences << "\n";
  } else {
    _PutLL(0, Occurences);
    _Send(0);
  }
}

int main() {
  MyInit();
  ComputeChunkHashes();
  ComputePatternPrefixHash();
  SendBackMyStats();
  CalculateResultForChunk();
  Final();

  //  for (int i = 0; i < P; ++i) {
  //    std::cerr << " total sent: " << TotalSent[i] << "\n";
  //  }
}