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

using namespace std;

#define DEBUG false
#define log if (DEBUG) cerr
typedef long long ll;
typedef unsigned long long ull;

const ll INF_LL = 9223372036854775807LL;


static ll signalLength, seqLength;


static int KMP(int seqOffset, int seqPieceLength)
{
    if (seqPieceLength == 0)
    {
        return 0;
    }
    vector<int> T(signalLength + 1, -1);
    int matches = 0;

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

    int sp = 0;
    int kp = 0;
    while (sp < seqPieceLength)
    {
        while (kp != -1 && (kp == signalLength || SignalAt(kp + 1) != SeqAt(seqOffset + sp + 1)))
        {
            kp = T[kp];
        }
        kp ++;
        sp ++;
        if (kp == signalLength)
        {
            matches ++;
        }
    }

    return matches;
}


int main()
{
    int myNodeId = MyNodeId();
    int numberOfNodes = NumberOfNodes();
    signalLength = SignalLength();
    seqLength = SeqLength();
    ll starts = seqLength - signalLength + 1;

    ll from = myNodeId * starts / numberOfNodes;
    ll to = (myNodeId + 1) * starts / numberOfNodes;
    ll seqPieceLength = to - from + signalLength - 1;

    log << "Node " << myNodeId << ": fr=" << from << ", to=" << to << ", pi=" << seqPieceLength << endl;
    int partialResult = KMP(from, seqPieceLength);
    log << "Node " << myNodeId << ": res=" << partialResult << endl;

    PutInt(0, partialResult);
    Send(0);

    if (myNodeId == 0)
    {
        ll result = 0;
        for (int i = 0; i < numberOfNodes; i++)
        {
            Receive(i);
            result += GetInt(i);
        }
        cout << result;
    }

    return 0;
}