-
Notifications
You must be signed in to change notification settings - Fork 0
/
Karp-Rabin.cpp
113 lines (66 loc) · 1.81 KB
/
Karp-Rabin.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <bits/stdc++.h>
using namespace std;
const int ModAdler = 65521;
long long adler32Hash (string& s){
int a = 1;
int b = 0;
for(int i=0;i<s.size();i++){
a+= ((int)s[i])%ModAdler;
b+= a%ModAdler;
}
long long x = b<<16;
x = x|a;
return x;
}
long long Adler32Update(long long x,string& s, int index){
long long xa = x;
long long xb = x;
int b = xb>>16;
xa=xa<<16;
xa=xa>>16;
int a = (int) xa;
a += (s[index]-s[index-s.length()]);
b += (s[index]-s.length()*(s[index-s.length()]));
long long newhash = b<<16 | a;
return newhash;
}
long long LargePrime = 109;
long long Base = 256;
int ModPower(int x, int n, int M) {
if(n==0) return 1;
else if(n%2 == 0)
return ModPower((x*x) % M, n/2, M);
else
return (x*ModPower((x*x) % M, (n-1)/2, M)) % M;
}
int Hash (string& s){
int h = 0;
for(int i=0;i<s.size();i++){
h = (h + ((int)s[i])*ModPower(Base,s.size()-i-1,LargePrime))%LargePrime;
}
return h;
}
int HashUpdate (long long h, string& text,int index,int l){
int len = l;
int cRemove = (((int)text[index-len])*ModPower(Base,len-1,LargePrime))%LargePrime;
int newH = (((h - cRemove)*Base)%LargePrime + (int)(text[index]))%LargePrime;
return newH;
}
int main(){
string p = "Aditya";
string q = "AmoghSagarAdityaRajRohit";
int hashP = Hash(p);
string k = q.substr(0,p.size());
int hash = Hash(k);
for(int i=p.size();i<q.size();i++){
if(hash==hashP){
if(q.substr(i-p.size(),p.size()) == p){
cout<<"Yes!"<<"\n";
return 0;
}
}
hash = HashUpdate(hash,q,i,p.size());
}
cout<<"No :(";
return 0;
}