Introduction To Algorithms Chap 32-2
//比较模同余时注意可能为负数等价类,将负数转为正数再比较
#include<iostream>
#include<cstring>
using namespace std;
#define d 128
#define q 13
int RabinKarp(char s[], char pat[]) {
long long m = strlen(pat), n = strlen(s);
long long t[100] = { 0 }, p = 0, pow = 1, tok = 0;
for (int i = 0; i < m; i++) {
t[0] = (d*t[0] + s[i]) % q;
p = (d*p + pat[i])%q;
}
for (int i = 1; i < m; i++) {
pow = (pow*d) % q;
}
for (int i = 0; i < n - m + 1; i++) {
if (p == t[i]||p==t[i]+q) { //负数取模后可能为负数,而p>0,但此时可能p和t模q同余,所以将p与t和t+q(模q等价类)比较,分情况
for (int j = 0; j < m; j++) {
if (s[j + i] != pat[j]) {
tok = 1;
continue;
}
}
if (!tok) {
cout << "find in " << i + 1 << endl;
return i;
}
}
t[i + 1] = (d*(t[i] - pow*s[i]) + s[i + m])%q;
}
cout << "Not found" << endl;
return -1;
}
int main() {
while (true) {
char a[100], p[20];
cin >> a >> p;
RabinKarp(a, p);
}
return 0;
}