-
Notifications
You must be signed in to change notification settings - Fork 9
/
hashing.cpp
79 lines (69 loc) · 1.62 KB
/
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
// hashing.cpp
// Eric K. Zhang; December 21, 2017
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL, LL> pll;
const int MOD = 1e9 + 7;
const pll BASE = {4441, 7817};
pll operator+(const pll& a, const pll& b) {
return { (a.first + b.first) % MOD, (a.second + b.second) % MOD };
}
pll operator+(const pll& a, const LL& b) {
return { (a.first + b) % MOD, (a.second + b) % MOD };
}
pll operator-(const pll& a, const pll& b) {
return { (MOD + a.first - b.first) % MOD, (MOD + a.second - b.second) % MOD };
}
pll operator*(const pll& a, const pll& b) {
return { (a.first * b.first) % MOD, (a.second * b.second) % MOD };
}
pll operator*(const pll& a, const LL& b) {
return { (a.first * b) % MOD, (a.second * b) % MOD };
}
pll get_hash(string s) {
pll h = {0, 0};
for (int i = 0; i < s.size(); i++) {
h = BASE * h + s[i];
}
return h;
}
struct hsh {
int N;
string S;
vector<pll> pre, pp;
void init(string S_) {
S = S_;
N = S.size();
pp.resize(N);
pre.resize(N + 1);
pp[0] = {1, 1};
for (int i = 0; i < N; i++) {
pre[i + 1] = pre[i] * BASE + S[i];
if (i) { pp[i] = pp[i - 1] * BASE; }
}
}
pll get(int s, int e) {
return pre[e] - pre[s] * pp[e - s];
}
};
vector<int> search(string s, string p) {
vector<int> matches;
pll h = get_hash(p);
hsh hs; hs.init(s);
for (int i = 0; i + p.size() <= s.size(); i++) {
if (hs.get(i, i + p.size()) == h) {
matches.push_back(i);
}
}
return matches;
}
int main() {
string S = "GGGATTCGGGTAAAGAGCGTGTTATTGGGGACTTACACAGGCGTAGACTA";
string P = "GG";
vector<int> v = search(S, P);
for (int idx : v) {
cout << idx << endl;
}
return 0;
}