Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- #include <algorithm>
- #include <string>
- using namespace std;
- const int q = 65536;
- int hashc(string s, int a, int b) {
- int n = b - a;
- int sum = 0;
- for (int i = 0; i < n; ++ i) {
- sum += s[a + i] * (int)pow(2, n - i - 1);
- }
- sum %= q;
- return sum;
- }
- int RABINKarp(string s, string t) {
- int n = s.size();
- int m = t.size();
- int h = hashc(t, 0, m);
- for (int i = 0; i < n - m + 1; ++ i) {
- if (h == hashc(s, i, i + m)) {
- bool eq = true;
- for (int j = 0; j < m; ++ j)
- if (s[i + j] != t[j])
- eq = false;
- if (eq) return i;
- }
- }
- return -1;
- }
- int main() {
- string s, t;
- cin >> s >> t;
- cout << RABINKarp(s, t) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement