forked from rishabhgarg25699/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRabin_Karp.cpp
94 lines (91 loc) · 1.96 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
92
93
94
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll polyhash(string S,ll p,ll x) //Using Polynomial Hash
{
ll hash=0;
for(ll i=S.length()-1;i>=0;i--)
{
hash=(((hash*x))+(S[i]))%p;
}
return hash;
}
vector <ll> precomputehashes(string T,ll pl,ll p,ll x)
{
vector<ll> H;
for(ll i=0;i<(T.length()-pl+1);i++)
{
H.push_back(0);
}
string S;
S=T.substr(T.length()-pl,pl);
H[T.length()-pl]=polyhash(S,p,x);
ll y=1;
for(ll i=1;i<=pl;i++)
{
y=((y)*(x))%p;
}
for(ll i=T.length()-pl-1;i>=0;i--)
{
ll prehash=(((((x)*(H[i+1])))+((T[i])))-(((y)*(T[i+pl]))));
while(prehash<0)
{
prehash+=p;
}
H[i]=prehash%p;
}
return H;
}
bool areequal(string s1,string s2) //To check that the two strings entered are equal
{
if(s1.length()!=s2.length())
{
return false;
}
for(ll i=0;i<s1.length();i++)
{
if(s1[i]!=s2[i])
return false;
}
return true;
}
vector<ll> RabinKarp(string T,string P)
{
ll p=1000000007;
ll x=rand()%(p-1)+1;
vector<ll> result;
ll phash=polyhash(P,p,x);
vector<ll> H;
H=precomputehashes(T,P.length(),p,x);
for(ll i=0;i<=(T.length()-P.length());i++)
{
if(phash!=H[i])
continue;
if(areequal(T.substr(i,P.length()),P))
{
result.push_back(i);
}
}
return result;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string P,T; //Enter Pattern as P and Text as t
cin>>P>>T;
vector<ll> result;
result=RabinKarp(T,P);
for(ll i=0;i<result.size();i++)
{
cout<<result[i]<<" ";
}
cout<<endl;
return 0;
}
/* Input: pattern and text
Output: All occurences of the pattern in the test
Input: aba
abacaba
Output: 0 4 */