Cod sursa(job #2817001)

Utilizator catalintermureTermure Catalin catalintermure Data 12 decembrie 2021 18:08:09
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <fstream>
#include <vector>
#include <algorithm>

class HashSet {
public:
  HashSet() {
    element_count_ = 0;
    bucket_count_ = 640000;
    buckets_ = std::vector<std::vector<int>>(bucket_count_);
  }

  void Add(int x) {
    if (Exists(x)) return;

    element_count_++;
/*    constexpr float max_load_factor = 0.75f;
    float load_factor = (float) bucket_count_ / element_count_;
    if (load_factor > max_load_factor) {
      Resize(bucket_count_ * 2);
    }
    else if (load_factor < max_load_factor / 4) {
      Resize(bucket_count_ / 2);
    }
*/
    UncheckedAdd(x);
  }

  void Remove(int x) {
    int hash = Hash(x);
    buckets_[hash].erase(std::remove(buckets_[hash].begin(), buckets_[hash].end(), x), buckets_[hash].end());
  };

  bool Exists(int x) {
    int hash = Hash(x);
    return std::find(buckets_[hash].begin(), buckets_[hash].end(), x) != buckets_[hash].end();
  }

private:
  std::vector<std::vector<int>> buckets_;
  size_t bucket_count_;
  size_t element_count_;

  int Hash(int x) {
    return x % bucket_count_;
  }

  void Resize(int new_size) {
    bucket_count_ = new_size;
    buckets_.resize(new_size);
    for (auto& bucket : buckets_) {
      if (bucket.empty()) continue;
      std::vector<int> values = bucket;
      bucket.clear();
      for (const auto value : values) {
        UncheckedAdd(value);
      }
    }
  }

  void UncheckedAdd(int x) {
    buckets_[Hash(x)].push_back(x);
  }
};

int main() {
  std::ifstream inf("hashuri.in");
  std::ofstream outf("hashuri.out");

  HashSet hash_set;
  int op_cnt, op_code, val;
  inf >> op_cnt;
  for (int i = 0; i < op_cnt; i++) {
    inf >> op_code >> val;
    if (op_code == 1) hash_set.Add(val);
    if (op_code == 2) hash_set.Remove(val);
    if (op_code == 3) outf << hash_set.Exists(val) << '\n';
  }

  inf.close();
  outf.close();
  return 0;
}