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

#include <cstdio>

using namespace std;

int main() {
    long long n = SeqLength();
    long long m = SignalLength();

    if (MyNodeId() != 0) {
        return 0;
    }

    int res = 0;
    if (m <= 1000000) {
        int pi[m + 1];
        pi[1] = 0;
        int k = 0;
        for (int q = 2; q <=m; q++) {
            while ((k > 0) && (SignalAt(k + 1) != SignalAt(q))) {
                k = pi[k];
            }
            if (SignalAt(k + 1) == SignalAt(q)) {
                k++;
            }
            pi[q] = k;
        }

        int q = 0;
        for (int i = 1; i <= n; i++) {
            while ((q > 0) && (SignalAt(q + 1) != SeqAt(i))) {
                q = pi[q];
            }
            if (SignalAt(q + 1) == SeqAt(i)) {
                q++;
            }
            if (q == m) {
                res++;
                q = pi[q];
            }
        }
    }
    else {
        long long d = 10000;
        long long q = 10657;
        long long h = 1;
        long long p = 0;
        long long t = 0;
        for (int i = 0; i < m - 1; i++) {
            h = (h * d) % q;
        }
        for (int i = 1; i <= m; i++) {
            p = (d * p + SignalAt(i)) % q;
            t = (d * t + SeqAt(i)) % q;
        }
        for (int s = 0; s <= n - m; s++) {
            if (p == t) {
                bool match = true;
                for (int i = 1; i <= m; i++) {
                    if (SignalAt(i) != SeqAt(s + i)) {
                        match = false;
                        break;
                    }
                }
                if (match) {
                    res++;
                }
            }
            if (s < n - m) {
                t = (d * (t - SeqAt(s + 1) * h) + SeqAt(s + m + 1)) % q;
                if (t < 0) {
                    t = (t + q);
                }
            }
        }
    }
    printf("%d\n", res);

    return 0;
}