Alex_tz307

Rabin-Karp

Sep 10th, 2020
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MAXN 2000001
  3. #define P 73
  4. #define MOD1 100007
  5. #define MOD2 100021
  6.  
  7. using namespace std;
  8.  
  9. ifstream fin ("strmatch.in");
  10. ofstream fout ("strmatch.out");
  11.  
  12. string A, B;
  13. int NA, NB;
  14. int hashA1, hashA2, P1, P2;
  15. char match[MAXN];
  16.  
  17. int main() {
  18.     fin >> A >> B;
  19.     NA = A.size(), NB = B.size();
  20.     if (NA > NB) {
  21.         fout << "0\n";
  22.         return 0;
  23.     }
  24.  
  25.     P1 = P2 = 1;
  26.     hashA1 = hashA2 = 0;
  27.     for (int i = 0; i < NA; i ++) {
  28.         hashA1 = (hashA1 * P + A[i]) % MOD1;
  29.         hashA2 = (hashA2 * P + A[i]) % MOD2;
  30.         if (i != 0)
  31.             P1 = (P1 * P) % MOD1, P2 = (P2 * P) % MOD2;
  32.     }
  33.  
  34.     int hash1 = 0, hash2 = 0;
  35.     for (int i = 0; i < NA; i++)
  36.         hash1 = (hash1 * P + B[i]) % MOD1, hash2 = (hash2 * P + B[i]) % MOD2;
  37.  
  38.     int Nr = 0;
  39.     if (hash1 == hashA1 && hash2 == hashA2)
  40.         match[0] = 1, Nr ++;
  41.  
  42.     for (int i = NA; i < NB; i ++) {
  43.         hash1 = ((hash1 - (B[i - NA] * P1) % MOD1 + MOD1) * P + B[i]) % MOD1;
  44.         hash2 = ((hash2 - (B[i - NA] * P2) % MOD2 + MOD2) * P + B[i]) % MOD2;
  45.         if (hash1 == hashA1 && hash2 == hashA2)
  46.             match[ i - NA + 1 ] = 1, Nr ++;
  47.     }
  48.     fout << Nr << '\n';
  49.  
  50.     Nr = 0;
  51.     for (int i = 0; i < NB && Nr < 1000; i ++)
  52.         if (match[i])
  53.             Nr ++, fout << i << ' ';
  54.     return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment