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
// based on Galil-Seiferas algorithm implementation from http://www-igm.univ-mlv.fr/~lecroq/string/node25.html
#include <cstdio>
#include "poszukiwania.h"
#include "message.h"

long long k, m, n, p, p1, p2, q, q1, q2, s;
long long start;
long long result;


int compare(long long cnt) {
	for (int i = 1; i <= cnt; ++i) {
		if (SignalAt(i) != SeqAt(start + p + i)) {
			return 1;
		}
	}
	return 0;
}

void search() {
   while (p <= n - m) {
      while (p + s + q < n && SignalAt(s + q + 1) == SeqAt(start + p + s + q + 1))
         ++q;
      if (q == m - s && compare(s + 1) == 0)
         ++result;
      if (q == p1 + q1) {
         p += p1;
         q -= p1;
      }
      else {
         p += (q/k + 1);
         q = 0;
      }
   }
}

void newP1();

void parse() {
   while (1) {
      while (SignalAt(s + q1 + 1) == SignalAt(s + p1 + q1 + 1))
         ++q1;
      while (p1 + q1 >= k*p1) {
         s += p1;
         q1 -= p1;
      }
      p1 += (q1/k + 1);
      q1 = 0;
      if (p1 >= p2)
         break;
   }
   newP1();
}
 

void newP2() {
   while (SignalAt(s + q2 + 1) == SignalAt(s + p2 + q2 + 1) && p2 + q2 < k*p2)
      ++q2;
   if (p2 + q2 == k*p2)
      parse();
   else
      if (s + p2 + q2 != m) {
         if (q2 == p1 + q1) {
            p2 += p1;
            q2 -= p1;
         }
         else {
            p2 += (q2/k + 1);
            q2 = 0;
         }
         newP2();
      }
}
 

void newP1() {
   while (SignalAt(s + q1 + 1) == SignalAt(s + p1 + q1 + 1))
      ++q1;
   if (p1 + q1 >= k*p1) {
      p2 = q1;
      q2 = 0;
      newP2();
   }
   else {
      if (s + p1 + q1 != m) {
         p1 += (q1/k + 1);
         q1 = 0;
         newP1();
      }
   }
}

int main() {
   m = SignalLength();
   n = SeqLength();
   k = 4;
   p = q = s = q1 = p2 = q2 = 0;
   p1 = 1;
   result = 0;

   int nodesNumber = NumberOfNodes();
   long long sizePerNode = ((SeqLength() - m + 1) + nodesNumber - 1) / nodesNumber;
   start = sizePerNode * MyNodeId();
   n = sizePerNode;
   if (start >= (SeqLength() - m + 1)) {
	   n = -m + 1;
   } else if (start + n > (SeqLength() - m + 1)) {
	   n = (SeqLength() - m + 1) - start;
   }
   n += m - 1;


   if (n > 0) {
	   newP1();
	   search();
   }

   if (MyNodeId() != 0) {
	   PutLL(0, result);
	   Send(0);
   } else {
	   for (int i = 1; i < nodesNumber; ++i) {
		   int src = Receive(-1);
		   result += GetLL(src);
	   }
	   printf("%lld\n", result);
   }

   return 0;
}