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
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cassert>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
#include <queue>
#include <bitset>
#include <utility>
#include <stack>

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

using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef vector<int> VI;
#define MP make_pair
#define FOR(v,p,k) for(auto v=(p);v<=(k);++v)
#define FORD(v,p,k) for(auto v=(p);v>=(k);--v)
#define REP(i,n) for(auto i=0;i<(n);++i)
#define VAR(v,i) __typeof(i) v=(i)
#define FOREACH(i,c) for(VAR(i,(c).begin());i!=(c).end();++i)
#define PB push_back
#define ST first
#define ND second
#define SIZE(x) (int)x.size()
#define ALL(c) c.begin(),c.end()

#define ODD(x) ((x)%2)
#define EVEN(x) (!(ODD(x)))


LL text_len, pattern_len;
int pattern_len_int;

inline LL TextAt(LL i) { return SeqAt(i+1);}
inline LL PatternAt(LL i) { return SignalAt(i+1);}

LL MOD = 1000000087LL;
LL X = 1000001053LL;

struct Ha {
    LL val = 0LL;
    Ha() : val(0LL) {}
    Ha(LL v) : val(v) {}

    inline bool operator==(const Ha& other) const {
      return val == other.val;
    }

    inline int asInt() const {
      return (int) val;
    }

    inline void updateRight(LL next, LL xx = X) {
        val = (val * xx + next) % MOD;
    }
    inline void updateRight(const Ha &next, LL xx = X) {
        updateRight(next.val, xx);
    }

    inline void updateLeft(LL next, LL xx) {
        LL a = (next * xx) % MOD;
        val = (val + MOD - a) % MOD;
    }

    inline void add(LL next) {
        val = (val + next) % MOD;
    }

    inline void add(const Ha &next) {
        add(next.val);
    }


    inline void multX(LL ex) {
        LL a = Ha(X).pow(ex).val;
        val = (val * a) % MOD;
    }

    //TODO moze jednak nie inline?
    inline Ha pow(LL ex) const {
        LL res = 1LL;
        LL val_copy = val;
        while (ex > 0) {
            if (ex % 2) res = (res * val_copy) % MOD;
            val_copy = (val_copy * val_copy) % MOD;
            ex /= 2;
        }
        return Ha{res};
    }

};

//X**M-1 = 1 mod M (Fermat): X * X_REV = 1 mod M
LL X_REV = Ha{X}.pow(MOD-2).val;

//zaadaptowane z http://www-users.mat.umk.pl/~stencel/acm/algorytmika_praktyczna.pdf
void KMP(int text_first_pos, int text_last_pos, int &res) {
  VI p(pattern_len_int+1);
  int k = 0;

  FOR(q,1,pattern_len_int-1) {
      while(k > 0 && PatternAt(k) != PatternAt(q)) k = p[k-1]; if(PatternAt(k) == PatternAt(q)) k++;
      p[q] = k;
  }

  k=0;
  FOR(q,text_first_pos, text_last_pos) {
    while(k > 0 && PatternAt(k) != TextAt(q)) k = p[k]; if(PatternAt(k) == TextAt(q)) k++;
    if (k==pattern_len_int) {
      //printf("pos %d\n", q);
      ++res;
      k=p[k];
    }
  }

}

struct Interval {
  LL firstTextPos, lastTextPos;
  vector<pair<LL,int>> extra;
  vector<Ha> extraHashesComputed;
  Ha lastComputed;
  Ha hashOfFirstPattern;
  LL firstPatternLastPos;
  int firstPatternLastPosInterval;
  int firstPatternLastPosIntervalVectorPos;

};

int main() {
  int nodesNumber = NumberOfNodes();
  int nodeID = MyNodeId();

  text_len = SeqLength();
  pattern_len = SignalLength();
  pattern_len_int = pattern_len;

  int res{};

  if (text_len <= 10000000LL) {
    //tak na wszelkie wypadek na jednym to puscmy, aby zredukowac szanse bledu
    if (nodeID == 0) KMP(0, text_len-1, res);
    //moze trzeba tutaj zrobic, aby max 10mln zapisywac liczb, bo jest limit 128MB pamieci, jesli tak to trzeba zobaczyc czy nie psuje tego, ze za duzo punktow posrednich wyjdzie
  } else if ((pattern_len <= (text_len / nodesNumber)) && (pattern_len <= 20000000LL)) {
    //caly czas myslmy o domknietych przedzialach
    //kazdy wczytuje caly pattern i tworzy tablice prefiksowa od kmp
    //nastepnie dzielimy text po rowno [0, text_len - pattern_len -1] i kazdy dla swojego przedzialu [x,y] sprawdza czy tutaj nie zaczyna sie wzorzec
    LL patternLeftPosRangeSize = text_len - pattern_len + 1;
    LL firstTextPos = (patternLeftPosRangeSize * nodeID) / nodesNumber;
    LL lastTextPos = (patternLeftPosRangeSize * (nodeID+1)) / nodesNumber + pattern_len -2;
    //kazdy swoj wynik zapisuje w zmiennej res
    KMP(firstTextPos, lastTextPos, res);
  } else {
    //dzielimy po rowno [0, pattern_len-1] i kazdy wczytuje swoj kawalek
    LL firstPatternPos = (pattern_len * nodeID) / nodesNumber;
    LL lastPatternPos = (pattern_len * (nodeID+1)) / nodesNumber -1;
    Ha patternPartHash;
    FOR(patternPos, firstPatternPos, lastPatternPos) {
      patternPartHash.updateRight(PatternAt(patternPos));
    }
    //przy wczytywaniu liczymy hash kawalka pomnozony przez hash (X**poczatek_przedzialu)
    //TODO zajrzec czy na pewno dobrze jest
    patternPartHash.multX((pattern_len - 1) - lastPatternPos);

    Ha patternHash;
    if (nodeID > 0) {
      //wszyscy oprocz 0 wysylaja hash kawalka
      PutInt(0, patternPartHash.asInt());
      Send(0);

      //wszyscy oprocz 0 odbieraja i zapamietuja hash wzorca
      int receivedNodeID = Receive(0);
      patternHash.add(GetInt(receivedNodeID));
    } else {
      //0 ma swoj i dodaje hashe modulo
      patternHash.add(patternPartHash);
      REP(i, nodesNumber - 1) {
        int receivedNodeID = Receive(-1);
        patternHash.add(GetInt(receivedNodeID));
      }

      //0 wysyla wszystkim oprocz siebie hash wzorca
      FOR(i, 1, nodesNumber - 1) {
        PutInt(i, patternHash.asInt());
        Send(i);
      }
    }

    LL defaultRangeLen = text_len/nodesNumber;
    vector<Interval> intervals(nodesNumber);
    REP(each_node, nodesNumber) {
      auto &inter = intervals[each_node];

      //dzielimy tekst [0, text_len-1] po rowno, tak aby co najwyzej ostatni przedzial byl dluzszy
      inter.firstTextPos = defaultRangeLen * each_node;
      inter.lastTextPos = defaultRangeLen * (each_node+1) -1;
      if (each_node == nodesNumber-1) inter.lastTextPos = text_len-1;

      //ponadto patrzymy do jakich przedzialow wpadaja punkty {lewy koniec ww przedzialu + pattern_len -1} i moze dojsc kilka takich punktow posrednich
      LL patternEnd = inter.firstTextPos + pattern_len -1;
      if (patternEnd <= text_len -1) {
        inter.firstPatternLastPos = patternEnd;
        int where = patternEnd/defaultRangeLen;
        intervals[where].extra.PB(MP(patternEnd, each_node));
        inter.firstPatternLastPosInterval = where;
        inter.firstPatternLastPosIntervalVectorPos = intervals[where].extra.size()-1;
      } else {
        inter.firstPatternLastPos = -42;
      }
    }
    //wtedy taki jeden worker liczy hash calego swojego przedzialu jak i kazdego z przedzialow [lewy, posredni], takich przedzialow moze byc 0, 1, 2 ... 20
    {
      auto &inter = intervals[nodeID];
      LL curr_pos = inter.firstTextPos;
      inter.extraHashesComputed.reserve(inter.extra.size());
      Ha textHash;
      textHash.updateRight(TextAt(curr_pos));
      for (auto &ext : inter.extra) {
          while (curr_pos < ext.first) textHash.updateRight(TextAt(++curr_pos));
          inter.extraHashesComputed.PB(textHash);
      }
      while (curr_pos < inter.lastTextPos) textHash.updateRight(TextAt(++curr_pos));
      inter.lastComputed = textHash;
    }

    //wszystie te hashe trzeba wyslac do 0, ktory musi je ladnie pozlaczac w nodesNumber hashy przedzialow o dlugosci pattern_len
    if (nodeID > 0) {
      auto &inter = intervals[nodeID];

      for (auto &ext : inter.extraHashesComputed) {
        PutInt(0, ext.asInt());
      }
      PutInt(0, inter.lastComputed.asInt());
      Send(0);
    } else {
       REP(i, nodesNumber - 1) {
         int receivedNodeID = Receive(-1);
         auto &inter = intervals[receivedNodeID];

         inter.extraHashesComputed.reserve(inter.extra.size());
         REP(j, inter.extra.size()) {
           inter.extraHashesComputed.PB(Ha(GetInt(receivedNodeID)));
         }
         inter.lastComputed = Ha(GetInt(receivedNodeID));
      }

      //laczenie
      LL xx = Ha{X}.pow(defaultRangeLen).val;
      REP(i, nodesNumber) {
        auto &inter = intervals[i];
        if (inter.firstPatternLastPos == -42) continue;

        LL curr = inter.firstTextPos;
        int j = i;
        auto &interWithPatternLast = intervals[inter.firstPatternLastPosInterval];
        while (j < inter.firstPatternLastPosInterval) {
          inter.hashOfFirstPattern.updateRight(intervals[j].lastComputed, xx);
          ++j;
        }
        LL xxx = Ha(X).pow(interWithPatternLast.extra[inter.firstPatternLastPosIntervalVectorPos].first - interWithPatternLast.firstTextPos + 1).val;
        inter.hashOfFirstPattern.updateRight(interWithPatternLast.extraHashesComputed[inter.firstPatternLastPosIntervalVectorPos], xxx);
      }
    }
  
   //0 rozsyla te hashe przedzialow o dlugosci pattern_len
    if (nodeID == 0) {
      FOR(i, 1, nodesNumber - 1) {
        auto &inter = intervals[i];
        //if (inter.firstPatternLastPos == -42) continue;


        PutInt(i, inter.hashOfFirstPattern.asInt());
        Send(i);
      }
    } else {
      auto &inter = intervals[nodeID];
      //if (inter.firstPatternLastPos != -42) 
      {
        int receivedNodeID = Receive(0);
        inter.hashOfFirstPattern.add(GetInt(receivedNodeID));
      }
    }

    //kazdy worker ma poczatkowy hash, a potem liczy hash kroczacy dla swojego przedzialu (lewy koniec w przedziale prawy przesuniety o dlugosc przedzialu) robiac:
    //   odejmowanie z lewej strony przemnozonego przez X**{pattern_len-1}
    //   update_right tym co z prawej
    //jesli ktorys taki wyjdzie to zwiekszamy res o 1
    {
        auto &inter = intervals[nodeID];
        if (inter.firstPatternLastPos != -42) {
          LL xx_pattern = Ha{X}.pow(pattern_len - 1).val;
          Ha currHash = inter.hashOfFirstPattern;
          LL currLeft = inter.firstTextPos;
          LL currRight = currLeft + pattern_len -1;

          while (currLeft <= inter.lastTextPos) {
            //TODO moze warto doliczyc sprawdzanie skrajnych elementow, aby poprawic hasha?
            if (currHash == patternHash) {
              ++res;
              //printf("pos %d\n", currRight);
            }
            currHash.updateLeft(TextAt(currLeft), xx_pattern);
            ++currLeft;
            ++currRight;
            currHash.updateRight(TextAt(currRight));
          }

        }


    }
  }


  //kazdy oprocz 0 wysyla wynik do zerowego.
  //zerowy sumuje i wypisuje
  if (nodeID > 0) {
    PutInt(0, res);
    Send(0);
  } else {
    REP(i, nodesNumber - 1) {
      int receivedNodeID = Receive(-1);
      res += GetInt(receivedNodeID);
    }
    printf("%d\n", res);
  }

  return 0;
}