forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rabin_karp.cpp
91 lines (67 loc) · 1.52 KB
/
rabin_karp.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
82
83
84
85
86
87
88
89
90
91
#include<iostream>
using namespace std;
#define int long long int
const int mod = 1e9+7;
const int p = 31;
// binary exponentiation(a^b %m) - o(log b)
int powr(int a, int b){
int res = 1;
while(b){
if(b & 1LL){
res *= a;
res %= mod;
}
b /= 2;
a *= a;
a %= mod;
}
return res;
}
int inv(int a){
//a^-1 % m
//fermats little theorem
return powr(a, mod-2);
}
// hash function
int poly_hash_string(string s){
int p_powr = 1;
int hash = 0;
for(int i=0;i<s.size();i++){
hash += (p_powr*(s[i]-'a' + 1));
p_powr *= p;
p_powr *= mod;
hash %= mod;
}
return hash;
}
int32_t main(){
string text = "ababab", pat = "aba";
int pat_hash = poly_hash_string(pat);
int n = text.size(), m = pat.size();
int text_hash = poly_hash_string(text.substr(0,m));
// found at index 0
if( text_hash == pat_hash){
cout<<0;
}
// rolling hash
for(int i=1;i+m <= n;i++){
int new_hash = text_hash;
//[i-1] th
// removed the [i-m] char
new_hash = (new_hash - (text[i-1] - 'a' + 1) + mod) % mod;
//divide by p (make 1 power less)
new_hash *= inv(p);
new_hash %= mod;
//add
new_hash = new_hash + (text[i+m-1] - 'a' + 1) * powr(p, m-1);
new_hash %= mod;
if(new_hash == pat_hash){
cout<< i <<"\n";
}
text_hash = new_hash;
}
return 0;
}
/*
Output : 0
*/