Advertisement
adfasdfadsfasdf

Untitled

Mar 10th, 2023
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. ```cpp
  2. #include <iostream>
  3. #include <cmath>
  4. #include <unordered_set>
  5. #include <unordered_map>
  6.  
  7. using namespace std;
  8. typedef unsigned long long ull;
  9.  
  10. const int PRIME_CONST = 29;
  11. const ull MAX_SIZE = INT_MAX;
  12.  
  13. ull scratch_hash(string s) {
  14.     ull hash = 0;
  15.     for (short i = 0; i < s.length(); i++) {
  16.        hash = (PRIME_CONST * hash + s[i]) % MAX_SIZE;
  17.     }
  18.     return hash;
  19. }
  20.  
  21. int ground_truth(string latin, int len) {
  22.     hash<string> hasher;
  23.     unordered_set<size_t> mp;
  24.     for (short i = 0; i < len - 1; i += 1) {
  25.         string removed = latin.substr(0, i) + latin.substr(i + 2, len - 1);
  26.         mp.insert(hasher(removed));
  27.     }
  28.     return mp.size();
  29. }
  30.  
  31. void solve() {
  32.     int len;
  33.     string latin;
  34.     cin >> len >> latin;
  35.  
  36.     unordered_set<ull> mp;
  37.     ull prefix_hash = 0;
  38.     ull postfix_hash = 0;
  39.     ull old_bit_base = 1;
  40.  
  41.     for (int i = 0; i < len - 3; i += 1) {
  42.         old_bit_base = (old_bit_base * PRIME_CONST) % MAX_SIZE;
  43.     }
  44.  
  45.  
  46.     for (short i = 2; i < len; i += 1) {
  47.         postfix_hash = (postfix_hash * PRIME_CONST + latin[i]) % MAX_SIZE;
  48.     }
  49.  
  50.     ull hash;
  51.     for (short i = 0; i < len - 1; i += 1) {
  52.         string prefix_string = latin.substr(0, i);
  53.         string postfix_string = latin.substr(i + 2, len - 1);
  54.         string removed = prefix_string + postfix_string;
  55.  
  56.         hash = (prefix_hash + postfix_hash) % MAX_SIZE;
  57.  
  58.         cout << "On string: " << removed << " hash " << hash << " expected " << scratch_hash(removed) << endl;
  59.         cout << "Prefix : " << prefix_hash << " Postfix: " << postfix_hash << endl;
  60.         mp.insert(hash);
  61.         prefix_hash = (prefix_hash + latin[i] * old_bit_base) % MAX_SIZE;
  62.         postfix_hash = (postfix_hash - latin[i+2] * old_bit_base) % MAX_SIZE;
  63.         old_bit_base = (old_bit_base / PRIME_CONST) % MAX_SIZE;
  64.     }
  65.     cout << mp.size() << endl;
  66. }
  67.  
  68. int main() {
  69.     int n = 0;
  70.     cin >> n;
  71.     while (n--) {
  72.         solve();
  73.     }
  74.     return 0;
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement