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
#include "poszukiwania.h"
#include "message.h"

#include <vector>
#include <algorithm>
#include <iostream>
#include <stdio.h>

using namespace std;

int oblicz_kmp(vector<int> pattern, int start, int end) {
    vector<int> T(pattern.size() + 1, -1);
    int matches = 0;


    for(int i = 1; i <= pattern.size(); i++)
    {
        int pos = T[i - 1];
        while(pos != -1 && pattern[pos] != pattern[i - 1]) pos = T[pos];
        T[i] = pos + 1;
    }

    int sp = start;
    int kp = 0;
    while(sp < end)
    {
        int msgSp = SeqAt(sp+1);
        while(kp != -1 && (kp == pattern.size() || pattern[kp] != msgSp)) kp = T[kp];
        kp++;
        sp++;
        if(kp == pattern.size() && sp < end) {
            matches++;
        }
    }

    return matches;
}

int main() {

  int N = SeqLength();
  int M = SignalLength();
  int NODES = NumberOfNodes();
  int myId = MyNodeId();

  int znalezione_ciagi = 0;

    int elements = N - M;
    int element_per_node = elements / NODES;
    int start = element_per_node * myId;
    int end = start + element_per_node + M;
    if (myId == NODES-1 || end < 0) end = N;
    end = min(end, N);

//    printf("INPUT [%d] N=%d M=%d NODES=%d ==> N/NODES=%d \n", myId, N, M, NODES, N/NODES);
//    printf("DBG   [%d] START=%d   END=%d DIFF=%d \n", myId, start, end, end - start + M);

    vector<int> pattern(M);
    for (int i=0; i<M; ++i) pattern[i] = SignalAt(i+1);

    znalezione_ciagi = oblicz_kmp(pattern, start, end);

    if (myId > 0) {
    PutInt(0, znalezione_ciagi);
    Send(0);
  } else {  // MyNodeId == 0
    for (int instancja = 1; instancja < NODES; ++instancja) {
      Receive(instancja);
      znalezione_ciagi += GetInt(instancja);
    }

    printf("%d\n", znalezione_ciagi);
  }
  
  return 0;
}