nrk009

RABIN-KARP

May 3rd, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
  4. #define ll long long
  5. #define ld long double
  6. #define pb push_back
  7. #define fe first
  8. #define se second
  9. #define st(x) sort(x.begin(),x.end())
  10. #define rst(x) sort(x.rbegin(), x.rend())
  11. #define all(x) x.begin(),x.end()
  12. long double pi = 3.14159265358979323;
  13.  
  14. const double EPS = 1e-12;
  15. const int N = 1e6 + 1;
  16. const int mod = 1e9 + 7;
  17. const ll p = 31;
  18. ll power[N];
  19. ll mul(ll x , ll y)
  20. {
  21.     return ((x%mod)*(y%mod))%mod;
  22. }
  23. ll add(ll x , ll y)
  24. {
  25.     return (x%mod+y%mod)%mod;
  26. }
  27. ll sub(ll x , ll y)
  28. {
  29.     return ((x % mod - y % mod + mod))%mod;
  30. }
  31. void pre()
  32. {
  33.     power[0] = 1;
  34.     for(int i = 1 ; i <= N ; i++ )
  35.     {
  36.         power[i] = mul(p,power[i-1]);
  37.     }
  38. }
  39.  
  40. void hash_func(string const &s , string const &p)
  41. {
  42.  
  43.    
  44.    
  45.     ll hp = 0 ;
  46.     ll n = s.size();
  47.     ll pl = p.size();
  48.     for(int i = 0 ; i < p.size() ; i++ )
  49.     {
  50.         hp = add(hp,mul(p[i] - 'a' + 1 , power[i]));
  51.     }
  52.    
  53.         vector < ll > hs(n+1,0),ans;
  54.     for(int i = 0 ; i < s.size() ; i++ )
  55.     {
  56.        
  57.         hs[i+1] = add(hs[i],mul(s[i] - 'a' + 1 , power[i]));
  58.        
  59.     }
  60.    
  61.     for(int i = 0 ; i  <= n - pl  ; i++)
  62.     {
  63.         ll curr = sub(hs[i+pl] , hs[i]);
  64.         if(curr == mul(hp,power[i]))
  65.             ans.pb(i);
  66.     }  
  67.  
  68.     if(ans.empty())
  69.         cout << "\n";
  70.     else
  71.     {
  72.         //cout << ans.size() << "\n";
  73.         for(auto it : ans)
  74.         cout << it << "\n";
  75.         cout << "\n";
  76.     }
  77.     cout << "\n";
  78.  
  79.  
  80. }
  81.  
  82. int main()
  83. {
  84.     fast;
  85.     pre();
  86.     ll t;
  87.    
  88.     string s , p;
  89.     while(cin >> t)
  90.     {
  91.         cin >> p >> s;
  92.         hash_func(s,p);
  93.     }
  94.  
  95.  
  96.  
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
  103.  
  104.  
  105.  
  106.    
  107.     return 0;
  108.    
  109. }
Add Comment
Please, Sign In to add comment