Advertisement
MAGCARI

Rabin Karp

Jan 28th, 2023 (edited)
1,050
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. /*
  2.     Task    : _example
  3.     Author  : Phumipat C. [MAGCARI]
  4.     Language: C++
  5.     Created : 30 January 2023 [21:47]
  6. */
  7. #include<bits/stdc++.h>
  8. using namespace std;
  9. char a[1010],b[1010];
  10. int main(){
  11.     cin.tie(0)->sync_with_stdio(0);
  12.     cin.exceptions(cin.failbit);
  13.     cin >> a+1 >> b+1;
  14.     int lena = strlen(a+1),lenb = strlen(b+1);
  15.     int hasha = 0,hashb = 0;
  16.     for(int i=1;i<=lenb;i++){
  17.         hasha = ((hasha * 29) + (a[i] - 'a')) % 1000003;
  18.         hashb = ((hashb * 29) + (b[i] - 'a')) % 1000003;
  19.     }
  20.     int num = 1;
  21.     for(int i=1;i<=lenb-1;i++)
  22.         num = (num * 29) % 1000003;
  23.     for(int i=1;i<=lena-lenb;i++){
  24.         if(hasha == hashb){
  25.             bool ok = true;
  26.             for(int j=1;j<=lenb;j++){
  27.                 if(a[i+j-1] != b[j]){
  28.                     ok = false;
  29.                     break;
  30.                 }
  31.             }
  32.             if(ok){
  33.                 cout << "founded\n";
  34.                 return 0;
  35.             }
  36.         }
  37.         hasha -= ((a[i] - 'a') * num) % 1000003;
  38.         hasha += 1000003;
  39.         hasha %= 1000003;
  40.  
  41.         hasha = ((hasha * 29) + (a[i+lenb] - 'a')) % 1000003;
  42.     }
  43.     cout << "not found\n";
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement