Advertisement
Salman_CUET_18

Substring Frequency(LOJ)

Apr 20th, 2020
541
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. // In The Name of Almighty Allah
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. #define             fastio              ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
  5. #define             ff                  first
  6. #define             ss                  second
  7. #define             int                 long long
  8. #define             pb                  push_back
  9. #define             pf                  push_front
  10. #define             pii                 pair<int,int>
  11. #define             debug(x)            cout << #x << " --->> " << x << endl;
  12. #define             mod                 1000000009
  13. #define             inf                 1e18
  14. #define             clear(x)            memset(x,0,sizeof(x));
  15. void Salman()
  16. {
  17.     fastio;
  18. #ifndef ONLINE_JUDGE
  19.     freopen("input.txt", "r", stdin);
  20.     freopen("output.txt", "w", stdout);
  21. #endif
  22. }
  23. int Rabin_Karp(string text, string pattern)
  24. {
  25.     int n = text.size(), m  = pattern.size(), cnt = 0;
  26.     const int p = 31;
  27.  
  28.     vector<int>p_pow(m);
  29.     p_pow[0] = 1;
  30.  
  31.     for (int i = 1; i < m; i++)
  32.         p_pow[i] = (p_pow[i - 1] * p) % mod;
  33.  
  34.     int patt_hash = 0;
  35.     for (int i = 0; i < m; i++)
  36.         patt_hash = (patt_hash + (pattern[i] - 'a' + 1) * p_pow[i]) % mod;
  37.  
  38.     int curr_hash = 0;
  39.     for (int i = 0; i < m; i++)
  40.         curr_hash = (curr_hash + (text[i] - 'a' + 1) * p_pow[i]) % mod;
  41.     //after calculating the hash value of first window, now slide
  42.     for (int i = m; i < n; i++)
  43.     {
  44.         if (curr_hash == patt_hash) cnt++;
  45.         curr_hash = ( ((curr_hash - (text[i - m] - 'a' + 1)) / p) + ((text[i] - 'a' + 1) * p_pow[m - 1]) ) % mod;
  46.     }
  47.     if (curr_hash == patt_hash) cnt++;
  48.     return cnt;
  49. }
  50. main()
  51. {
  52.     Salman();
  53.     int tc; cin >> tc;
  54.     for (int i = 1; i <= tc; i++)
  55.     {
  56.         string text, pattern; cin >> text >> pattern;
  57.         cout << "Case " << i << ": " << Rabin_Karp(text, pattern) << endl;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement