Advertisement
smatskevich

HashSet

Feb 11th, 2023
727
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <forward_list>
  3. #include <string>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. int MyHash(const string& key) {
  9.   int result = 0;
  10.   for (int i = 0; i < min(key.size(), 5ul); ++i)
  11.     result = result * 37 + key[i];
  12.   return result;
  13. }
  14.  
  15. class HashSet {
  16.  public:
  17.   HashSet() : table(80) {}
  18.  
  19.   bool Has(const string& key) const;
  20.   // Возвращает false, если дубль.
  21.   bool Add(const string& key);
  22.   // Возвращает false, если ключа нет.
  23.   bool Remove(const string& key);
  24.  private:
  25.   vector<forward_list<string>> table;
  26. };
  27.  
  28. bool HashSet::Has(const string& key) const {
  29.   int hash = MyHash(key) % table.size();
  30.   auto& current_list = table[hash];
  31.   auto it = find(current_list.begin(), current_list.end(), key);
  32.   return it != current_list.end();
  33. }
  34. bool HashSet::Add(const string& key) {
  35.   int hash = MyHash(key) % table.size();
  36.   auto& current_list = table[hash];
  37.   auto it = find(current_list.begin(), current_list.end(), key);
  38.   if (it != current_list.end()) return false;
  39.   current_list.insert_after(current_list.before_begin(), key);
  40.   return true;
  41. }
  42. bool HashSet::Remove(const string& key) {
  43.   int hash = MyHash(key) % table.size();
  44.   auto& current_list = table[hash];
  45.   return current_list.remove(key);
  46. }
  47.  
  48. int main() {
  49.   HashSet hashset;
  50.   char command = 0;
  51.   string value;
  52.   while (cin >> command >> value) {
  53.     switch (command) {
  54.       case '?':
  55.         cout << (hashset.Has(value) ? "OK" : "FAIL") << endl;
  56.         break;
  57.       case '+':
  58.         cout << (hashset.Add(value) ? "OK" : "FAIL") << endl;
  59.         break;
  60.       case '-':
  61.         cout << (hashset.Remove(value) ? "OK" : "FAIL") << endl;
  62.         break;
  63.     }
  64.   }
  65.  
  66.   return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement