forked from ShahjalalShohag/code-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
String Hashing.cpp
81 lines (77 loc) · 2.08 KB
/
String Hashing.cpp
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
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 9;
int power(long long n, long long k, const int mod) {
int ans = 1 % mod;
n %= mod;
if (n < 0) n += mod;
while (k) {
if (k & 1) ans = (long long) ans * n % mod;
n = (long long) n * n % mod;
k >>= 1;
}
return ans;
}
const int MOD1 = 127657753, MOD2 = 987654319;
const int p1 = 137, p2 = 277;
int ip1, ip2;
pair<int, int> pw[N], ipw[N];
void prec() {
pw[0] = {1, 1};
for (int i = 1; i < N; i++) {
pw[i].first = 1LL * pw[i - 1].first * p1 % MOD1;
pw[i].second = 1LL * pw[i - 1].second * p2 % MOD2;
}
ip1 = power(p1, MOD1 - 2, MOD1);
ip2 = power(p2, MOD2 - 2, MOD2);
ipw[0] = {1, 1};
for (int i = 1; i < N; i++) {
ipw[i].first = 1LL * ipw[i - 1].first * ip1 % MOD1;
ipw[i].second = 1LL * ipw[i - 1].second * ip2 % MOD2;
}
}
struct Hashing {
int n;
string s; // 0 - indexed
vector<pair<int, int>> hs; // 1 - indexed
Hashing() {}
Hashing(string _s) {
n = _s.size();
s = _s;
hs.emplace_back(0, 0);
for (int i = 0; i < n; i++) {
pair<int, int> p;
p.first = (hs[i].first + 1LL * pw[i].first * s[i] % MOD1) % MOD1;
p.second = (hs[i].second + 1LL * pw[i].second * s[i] % MOD2) % MOD2;
hs.push_back(p);
}
}
pair<int, int> get_hash(int l, int r) { // 1 - indexed
assert(1 <= l && l <= r && r <= n);
pair<int, int> ans;
ans.first = (hs[r].first - hs[l - 1].first + MOD1) * 1LL * ipw[l - 1].first % MOD1;
ans.second = (hs[r].second - hs[l - 1].second + MOD2) * 1LL * ipw[l - 1].second % MOD2;
return ans;
}
pair<int, int> get_hash() {
return get_hash(1, n);
}
};
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
prec();
int n;
while (cin >> n) {
string s, p;
cin >> p >> s;
Hashing h(s);
auto hs = Hashing(p).get_hash();
for(int i = 1; i + n - 1 <= s.size(); i++) {
if (h.get_hash(i, i + n - 1) == hs) cout << i - 1 << '\n';
}
cout << '\n';
}
return 0;
}
// https://www.spoj.com/problems/NHAY/