trafik

hash

Dec 29th, 2021
1,070
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include "iostream"
  2. #include "vector"
  3. #include <string>
  4. #include <set>
  5.  
  6. using namespace std;
  7.  
  8. const int A = 1029;
  9. const long long B = 10e18+7;
  10. const long long C = 10e9+7;
  11.  
  12. typedef vector<long long> vi;
  13.  
  14. pair<long long , long long > get_sub_hash(vector<long long > h, vector<long long> p, long long l, long long r) {
  15.     if (l==0)
  16.         return {h[r]%C, h[r]%B};
  17.     long long pre_res = (h[r]-h[l-1]*p[r-l+1]);
  18.     return {pre_res%C, pre_res%B};
  19.  
  20. }
  21.  
  22. pair<vi, vi> hash_string(string s) {
  23.     int n=s.length();
  24.     vector<long long > h(n);
  25.     vector<long long > p(n);
  26.  
  27.     h[0] = s[0];
  28.     p[0] = 1;
  29.  
  30.     for (int i=1; i<n; i++) {
  31.         h[i] = ((h[i-1]*A+s[i]) % B);
  32.         p[i] = ((p[i-1]*A) % B);
  33.     }
  34.     return {h, p};
  35. }
  36.  
  37. int main() {
  38.     set<pair<long long ,long long>> nums;
  39.  
  40.     string s;
  41.     getline(cin, s);
  42.  
  43.     int n=s.length();
  44.  
  45.     vector<long long> h, p;
  46.     pair<vi, vi> hp =  hash_string(s);
  47.  
  48.  
  49.     for (int l=0; l<n; l++) {
  50.         for (int r=l; r<n; r++) {
  51.             nums.insert(get_sub_hash(hp.first, hp.second, l, r));
  52.         }
  53.     }
  54.     cout << nums.size() << endl;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment