-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrabin_karp_with_power.cpp
69 lines (63 loc) · 1.09 KB
/
rabin_karp_with_power.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
#include<iostream>
using namespace std;
#include<string>
#include<math.h>
int valueOf(char ch)
{
return (ch-'0');
}
bool check_characters(string T, string P, int s)
{
int n = T.length();
int m = P.length();
for(int i=0; i<m; i++)
{
if(P[i] != T[s+i])
return false;
}
return true;
}
void rabin_karp_matcher(string T, string P, int d, int q)
{
int i,s;
int n = T.length();
int m = P.length();
int h = 1;
int p = 0;
int t0 = 0;
for(i=0; i<m-1; i++)
{
h=(h*d)%q;
}
for(i=0;i<m;i++)
{
p=(d*p + valueOf(P[i]))%q;
t0=(d*t0 + valueOf(T[i]))%q;
}
for(s=0;s<=n-m;s++)
{
if(p==t0)
{
if(check_characters(T,P,s))
{
cout<<s<<endl;
}
}
if(s<n-m)
{
t0=(d*(t0-valueOf(T[s])*h)+valueOf(T[s+m]))%q;
if(t0<0)
{
t0+=q;
}
}
}
}
int main()
{
string T, P;
int d,q;
cin>>T>>P;
cin>>d>>q;
rabin_karp_matcher(T,P,d,q);
}