Advertisement
Josif_tepe

Untitled

Dec 12th, 2023
628
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. using namespace std;
  5. string pattern, text;
  6. const int B = 256;
  7. const int MOD = INT_MAX;
  8. void robin_carp() {
  9.     int hash_pattern = 0, hash_text = 0;
  10.     for(int i = 0; i < (int) pattern.size(); i++) {
  11.         hash_pattern = (B * hash_pattern + pattern[i]) % MOD;
  12.         hash_text = (B * hash_text + text[i]) % MOD;
  13.     }
  14.     cout << hash_pattern << " " << hash_text << endl;
  15.     int h = 1;
  16.     for(int i = 0; i < (int) pattern.size() - 1; i++) {
  17.         h = (h * B) % MOD;
  18.     }
  19.     for(int i = 0; i <= (int) text.size() - (int) pattern.size(); i++) {
  20.         if(hash_pattern == hash_text) {
  21.             bool ok = true;
  22.             for(int j = 0; j < (int) pattern.size(); j++) {
  23.                 if(text[i + j] != pattern[j]) {
  24.                     ok = false;
  25.                     break;
  26.                 }
  27.             }
  28.             if(ok) {
  29.                 cout << "found at: " << i << endl;
  30.             }
  31.            
  32.         }
  33.         if(i < (int) text.size() - (int) pattern.size()) {
  34.             hash_text = (B * (hash_text - text[i] * h) + text[i + (int) pattern.size()]) % MOD;
  35.             if(hash_text < 0) {
  36.                 hash_text += MOD;
  37.  
  38.             }
  39.         }
  40.     }
  41.    
  42. }
  43. int main() {
  44.     ios_base::sync_with_stdio(false);
  45.     cin >> pattern >> text;
  46.     robin_carp();
  47.     return 0;
  48. }
  49. /*
  50.  
  51.  **/
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement