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
// TNIEMY PAMIEC LOLOLOLOLOL!!!!
#include <bits/stdc++.h>
#include "message.h"
#include "poszukiwania.h"

//long long SeqLength(){ return 2000000000; }
//long long SignalLength(){ return 2000000000; }
//long long SeqAt(long long pos){ return (pos*pos)%123456789; }
//long long SignalAt(long long pos){ return (pos*pos)%123456789; }


using namespace std;

typedef long long LL;

template<typename TH>
void debug_vars(const char* data, TH head){
    cerr << data << "=" << head << "\n";
}

template<typename TH, typename... TA>
void debug_vars(const char* data, TH head, TA... tail){
    while(*data != ',') cerr << *data++;
    cerr << "=" << head << ",";
    debug_vars(data+1, tail...);
}

template<typename... TA>
void debugv(int line, const char* data, TA... tail){
    cerr << line << ": ";
    debug_vars(data, tail...);
}

#ifdef LOCAL
#define debug(...) debugv(__LINE__, #__VA_ARGS__, __VA_ARGS__)
#else
#define debug(...) (__VA_ARGS__)
#endif

/////////////////////////////////////////////////////////


const int SendAfter = 300;

struct Sender {
    enum FieldType { FLD_CHAR, FLD_INT, FLD_LL };
    struct field {
        FieldType type;
        union { char ch; int n; LL l; };
    };
    struct Submitter {};

    vector<field> toSend;
    int dest;
    int cap;

    Sender() : dest(-10000), cap(SendAfter) {}
    Sender(int dst){
        dest = dst;
        cap = SendAfter;
        toSend.clear();
    }
    ~Sender(){
        if(toSend.size() > 0) submit();
    }

    int capacity() const { return cap; }
    void capacity(int newCapacity) { cap = newCapacity; }
    
    void submit(){
        debug("sumbit to ", dest, toSend.size());
        if(toSend.size() == 0) return;
        PutInt(dest, (int)toSend.size());
        for(auto& f : toSend){
            switch(f.type){
                case FLD_CHAR: PutChar(dest, f.ch); break;
                case FLD_INT:  PutInt(dest, f.n); break;
                case FLD_LL:   PutLL(dest, f.l); break;
                default:       assert(false);
            }
        }
        Send(dest);
        toSend.clear();
    }

    void add_field(field f){
        assert(dest >= 0);
        toSend.push_back(f);
        if(toSend.size() >= cap) submit();
    }

    friend Sender& operator<<(Sender& snd, char ch){
        field f; f.type = FLD_CHAR; f.ch = ch; snd.add_field(f); return snd;
    }
    friend Sender& operator<<(Sender& snd, int n){
        field f; f.type = FLD_INT; f.n = n; snd.add_field(f); return snd;
    }
    friend Sender& operator<<(Sender& snd, LL l){
        field f; f.type = FLD_LL; f.l = l; snd.add_field(f); return snd;
    }
    friend Sender& operator<<(Sender& snd, Sender::Submitter){
        snd.submit(); return snd;
    }
};
Sender::Submitter submit;


struct Receiver {
    int numEnqueued;
    int node;

    Receiver() : node(-10000) {}
    Receiver(int nod) : node(nod), numEnqueued(0) {}

    void try_fetch(){
        assert(node >= -1);
        assert(numEnqueued >= 0);
        if(numEnqueued > 0){ numEnqueued--; return; }
        Receive(node);
        numEnqueued = GetInt(node);
        numEnqueued--;
    }

    char read_char(){ try_fetch(); return GetChar(node); }
    int read_int(){ try_fetch(); return GetInt(node); }
    LL read_ll(){ try_fetch(); return GetLL(node); }

    friend Receiver& operator>>(Receiver& recv, char& ch){
        ch = recv.read_char(); return recv;
    }
    friend Receiver& operator>>(Receiver& recv, int& n){
        n = recv.read_int(); return recv;
    }
    friend Receiver& operator>>(Receiver& recv, LL& l){
        l = recv.read_ll(); return recv;
    }
};

template<int Mod> inline int add_mod(int a, int b){ return (a+b)%Mod; }
template<int Mod> inline int sub_mod(int a, int b){ return (a-b+Mod)%Mod; }
template<int Mod> inline int mul_mod(int a, int b){ return ((LL)a*b)%Mod; }
template<int Mod> int pow_mod(int a, int n){
    int res = 1;
    while(n){
        if(n & 1) res = mul_mod<Mod>(res, a);
        n >>= 1; a = mul_mod<Mod>(a, a);
    }
    return res;
}


template<int Base, int Mod>
struct Hash {
    int value, length, curPow;

    Hash() : value(0), length(0), curPow(1) {}
    explicit Hash(int v) : value(v), length(1), curPow(Base) {}
    Hash(int v, int len) : value(v), length(len), curPow(pow_mod<Mod>(Base, len)) {}
    Hash(int v, int len, int p) : value(v), length(len), curPow(p) {}
    
    Hash<Base,Mod> operator+(int other) const {
        return Hash(add_mod<Mod>(value, mul_mod<Mod>(other, curPow)),
                    length+1,
                    mul_mod<Mod>(curPow, Base));
    }
    Hash<Base,Mod> operator+(const Hash<Base,Mod>& other) const {
        return Hash(add_mod<Mod>(value, mul_mod<Mod>(other.value, curPow)),
                    length+other.length,
                    mul_mod<Mod>(curPow, other.curPow));
    }
    Hash<Base,Mod> operator|(const Hash<Base,Mod>& other) const {
        return Hash(add_mod<Mod>(value,other.value), length, curPow);
    }
    Hash<Base,Mod> operator-(const Hash<Base,Mod>& other) const {
        return Hash(sub_mod<Mod>(value,other.value), length, curPow);
    }
    Hash<Base,Mod> operator<<(int dist) const {
        int p = pow_mod<Mod>(Base, dist);
        return Hash(mul_mod<Mod>(value,p), length+dist, mul_mod<Mod>(curPow,p));
    }
    Hash<Base,Mod> operator<<(pair<int,int> amount /*{dist,p}*/) const {
        return Hash(mul_mod<Mod>(value,amount.second),
                    length+amount.first,
                    mul_mod<Mod>(curPow,amount.second));
    }
    bool operator==(const Hash<Base,Mod>& other) const {
        return (value == other.value);
    }

    friend Sender& operator<<(Sender& snd, Hash<Base,Mod>& h){
        snd << h.value << h.length;
        return snd;
    }
    friend Receiver& operator>>(Receiver& recv, Hash<Base,Mod>& h){
        recv >> h.value >> h.length;
        h.curPow = pow_mod<Mod>(Base, h.length);
        return recv;
    }
};

constexpr const int Base1 = 91284712,
                    Base2 = 683194215,
                    Mod1  = 1008061463,
                    Mod2  = 1010101619;

struct HashPair {
    using H1 = Hash<Base1, Mod1>;
    using H2 = Hash<Base2, Mod2>;

    H1 h1; H2 h2;
    HashPair() : h1(), h2() {}
    explicit HashPair(int v) : h1(v), h2(v) {}
    HashPair(int v, int len) : h1(v,len), h2(v,len) {}
    HashPair(int v, int len, int p) : h1(v,len,p), h2(v,len,p) {}
    HashPair(H1 hash1, H2 hash2) : h1(hash1), h2(hash2) {}

    HashPair operator+(int other) const { return HashPair(h1+other, h2+other); }
    HashPair operator+(const HashPair& other) const {
        return HashPair(h1+other.h1, h2+other.h2);
    }
    HashPair operator|(const HashPair& other) const {
        return HashPair(h1|other.h1, h2|other.h2);
    }
    HashPair operator-(const HashPair& other) const {
        return HashPair(h1-other.h1, h2-other.h2);
    }
    HashPair operator<<(int dist) const {
        return HashPair(h1<<dist, h2<<dist);
    }
    HashPair operator<<(tuple<int,int,int> amount) const {
        return HashPair(h1<<make_pair(get<0>(amount),get<1>(amount)),
                        h2<<make_pair(get<0>(amount),get<2>(amount)));
    }
    bool operator==(const HashPair& other) const {
        return (h1 == other.h1) && (h2 == other.h2);
    }

    friend Sender& operator<<(Sender& snd, HashPair& h){
        //cerr << h.h1.value << " " << h.h2.value << endl;
        snd << h.h1 << h.h2; return snd;
    }
    friend Receiver& operator>>(Receiver& recv, HashPair& h){
        recv >> h.h1 >> h.h2; return recv;
    }
};


LL MyNode;
LL TotalNodes;
vector<Sender> senders;
vector<Receiver> receivers;

void init(){
    MyNode     = MyNodeId();
    TotalNodes = NumberOfNodes();
    for(LL i = 0; i < TotalNodes; i++){
        senders.emplace_back(i);
        receivers.emplace_back(i);
    }
}

const int Root = 0;

using SizeGetter = function<LL()>;
using ItemGetter = function<LL(LL)>;

// sgetter: funkcja zwracajaca dlugosc slowa
// igetter: funkcja bioraca element na danej pozycji
// indices: numery indeksow, dla ktorych chcemy policzyc hasze (rosnaco)
// hashes:  hasze kolejnych prefiksow slowa (od left-1 do right-1; left-1 to pusty)
// left:    pierwszy indeks przetworzonego slowa
// right:   pierwszy indeks po przetworzonym slowie
// repairHashes: czy naprawiac hasze, dodajac wynik uzyskany przez roota?
// (return) hasz calego slowa
HashPair process_word(SizeGetter sgetter, ItemGetter igetter,
                  const vector<LL>& indices,
                  vector<HashPair>& hashes, LL &left, LL &right,
                  bool repairHashes){
    left = right = -1;
    LL iptr = 0;  // iterator po indeksach

    LL S = sgetter();
    debug(S);
    if(MyNode >= S){
        // jesli jestem dalekim nodem, po prostu oczekuje na wynik od roota
        HashPair result; receivers[Root] >> result;
        return result;
    }
    LL numNodes = min(TotalNodes, S);
    left = (S * MyNode)/numNodes + 1;
    right = (S * (MyNode+1))/numNodes + 1;
    debug(numNodes, left, right);

    // liczymy hasze od pozycji left do right-1
    //hashes.resize(right-left+1, HashPair(0, left-1));  // NOPE
    HashPair lastHash(0, left-1);
    for(LL i = left; i < right; i++){
        LL pos = i-left+1;
        LL v = igetter(i);
        debug(v);
        lastHash = lastHash + v;
        //hashes[pos] = hashes[pos-1] + v;
        debug(pos, lastHash.h1.value, lastHash.h2.value);

        // wrzucamy do wynikow, jesli trzeba
        while(iptr < (int)indices.size() && indices[iptr] == i){
            hashes.push_back(lastHash);
            iptr++;
        }
    }

    // przesylamy rootowi 
    senders[0] << lastHash << submit;
    debug("sent to root from ", MyNode);

    // jesli jestem rootem, przetwarzam wyniki
    if(MyNode == Root){
        HashPair total(0, S);
        for(LL node = 0; node < TotalNodes; node++){
            if(node < numNodes){
                HashPair hp;
                debug("root reads from ", node);
                receivers[node] >> hp;         // wczytuje dane z noda
                debug("done reading from ", node);
                senders[node] << total;        // przesylam aktualna sume prefiksowa
                debug("submitted current from root to ", node);
                total = total | hp;            // uaktualniam wynik
            }
        }
        // przesylam jeszcze wszystkim nodom calkowity wynik
        for(LL node = 0; node < TotalNodes; node++){
            senders[node] << total << submit;
            debug("submitted total from root to ", node);
        }
    }

    // odbieram wynik; jesli mam poprawic, poprawiam
    HashPair result, myStart;
    debug("reading from root from ", MyNode);
    receivers[Root] >> myStart >> result;
    if(repairHashes){
        for(auto& hp : hashes){
            hp = hp | myStart;
            debug(hp.h1.value, hp.h1.length, hp.h1.curPow);
        }
    }

    return result;
}

vector<HashPair> myPatternHashes, myTextHashes;
HashPair ptnHash;
LL pleft, pright;
LL S, T, numNodes;


HashPair getHashAtText(LL pos, const vector<LL>& indices){
    debug("getHashAtText", pos);
    for(LL i = 0; i < (int)indices.size(); i++){
        if(indices[i] == pos) return myTextHashes[i];
    }
    assert(false);
}


int main(){
    S = SignalLength();
    T = SeqLength();
    init();
    ptnHash = process_word(SignalLength, SignalAt, {}, myPatternHashes,
                           pleft, pright, false);
    debug(ptnHash.h1.value, ptnHash.h2.value);

    myPatternHashes.clear(); myPatternHashes.shrink_to_fit();

    // uzyskujemy numerki haszy, ktore nas interesuja
    // potrzebujemy:
    // (*) pierwotnych pozycji, ktore przeslemy innym nodom
    // (*) naszej pierwotnej pozycji
    vector<LL> neededIndices;
    // najpierw my
    numNodes = min(T, TotalNodes);

    if(MyNode >= numNodes){
        // nie ma co robic, zwracamy 0
        senders[Root] << 0LL << submit;
        debug("goodbye oh cruel world");
        return 0;
    }

    pleft = (T * MyNode)/numNodes + 1;
    pright = (T * (MyNode+1))/numNodes + 1;
    LL rptr = max(S, pleft), lptr = rptr-S;
    debug(pleft, pright, lptr, rptr);
    if(pright-1 >= S){
        neededIndices.push_back(rptr);
    }
    // teraz inni, ktorzy nas potrzebuja
    for(LL otherNode = 0; otherNode < numNodes; otherNode++){
        LL otherLeft  = (T*otherNode)/numNodes+1,
           otherRight = (T*(otherNode+1))/numNodes+1;
        if(otherRight-1 < S) continue;
        LL otherRptr  = max(S, otherLeft),
           otherLptr  = otherRptr-S;
        if(pleft <= otherLptr && otherLptr <= pright-1){
            LL pos = otherLptr;
            neededIndices.push_back(pos);
        }
    }
    sort(neededIndices.begin(), neededIndices.end());
    neededIndices.resize(distance(neededIndices.begin(),
                unique(neededIndices.begin(), neededIndices.end())));
    for(int nid : neededIndices) debug(nid);


    HashPair tmpHash = process_word(SeqLength, SeqAt,
            neededIndices, myTextHashes, pleft, pright, true);
    debug(tmpHash.h1.value, tmpHash.h2.value);
    debug(pleft, pright, S);


    // przesylamy innym nodom informacje o poczatku ich przedzialu
    // zainteresowania
    for(LL otherNode = 0; otherNode < numNodes; otherNode++){
        LL otherLeft = (T * otherNode)/numNodes + 1,
           otherRight = (T * (otherNode+1))/numNodes + 1;
        if(otherRight-1 < S) continue;
        LL otherRptr = max(S, otherLeft),
           otherLptr = otherRptr-S;

        if(pleft <= otherLptr && otherLptr <= pright-1){
            LL pos = otherLptr;
            debug(pos);
            HashPair toSend = getHashAtText(pos, neededIndices);
            debug("submitting my hash info to ", otherNode, pos,
                    toSend.h1.length,
                    toSend.h1.curPow);

            senders[otherNode] << toSend << submit;
        }
    }

    if(pright-1 < S){
        // nie ma czego przeszukiwac
        senders[Root] << 0LL << submit;
        debug("trolololo doing nothing");
    } else {


        debug(rptr);
        HashPair HR = getHashAtText(rptr, neededIndices), HL;
            //myTextHashes[rptr-(pleft-1)]
        // odbieramy lewy hasz skads
        if(lptr != 0){
            for(LL otherNode = 0; otherNode < numNodes; otherNode++){
                LL otherLeft  = (T * otherNode)/numNodes + 1,
                   otherRight = (T * (otherNode+1))/numNodes + 1;
                if(otherLeft <= lptr && lptr <= otherRight-1){
                    debug("receiving asked hash info from ", otherNode);
                    receivers[otherNode] >> HL;
                    debug(HL.h1.value, HL.h1.length, HL.h1.curPow);
                }
            }
        }

        debug(HL.h1.length, HL.h1.curPow);

        LL matches = 0;
        ptnHash = (ptnHash << lptr);
        // przechodzimy pointerem, szukajac zgodnosci
        while(rptr < pright){
            debug(lptr, rptr);
            debug(HL.h1.value, HL.h2.value);
            debug(HR.h1.value, HR.h2.value);
            HashPair H = HR-HL;
            debug(H.h1.value, H.h2.value, ptnHash.h1.value, ptnHash.h2.value);
            if(H == ptnHash) matches++;
            ptnHash = (ptnHash << 1);
            lptr++; rptr++;
            if(rptr < pright){
                HL = HL + SeqAt(lptr);
                HR = HR + SeqAt(rptr);
            }
        }

        // slemy rootowi informacje o tym, jak bardzo sie udalo
        senders[Root] << matches << submit;

    }

    // jesli jestem rootem, odczytuje wszystko, sumuje i wypisuje
    if(MyNode == Root){
        LL result = 0;
        for(LL i = 0; i < TotalNodes; i++){
            debug(i);
            LL value;
            receivers[i] >> value;
            result += value;
        }
        cout << result << endl;
    }
}