Cod sursa(job #3131045)

Utilizator Nicoleta114Caramaliu Nicoleta Nicoleta114 Data 19 mai 2023 01:53:48
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;


class MyHashTable {
private:
    std::vector<std::vector<int>> buckets;
    int numBuckets;

    int hashFunction(int key) {
        return key % numBuckets;
    }

public:
    MyHashTable(int num) : numBuckets(num) {
        buckets.resize(numBuckets);
    }

    void insert(int key) {
        int index = hashFunction(key);
        for (int num : buckets[index]) {
            if (num == key) {
                return;
            }
        }
        buckets[index].push_back(key);
    }

    void erase(int key) {
        int index = hashFunction(key);
        std::vector<int>& bucket = buckets[index];
        for (auto it = bucket.begin(); it != bucket.end(); ++it) {
            if (*it == key) {
                bucket.erase(it);
                return;
            }
        }
    }

    bool contains(int key) {
        int index = hashFunction(key);
        for (int num : buckets[index]) {
            if (num == key) {
                return true;
            }
        }
        return false;
    }
};

int main() {
    int N, op, x;
    std::ifstream f("hashuri.in");
    std::ofstream g("hashuri.out");
    f >> N;
    MyHashTable hashTable(200000);

    for (int i = 0; i < N; i++) {
        f >> op >> x;
        if (op == 1) {
            hashTable.insert(x);
        } else if (op == 2) {
            hashTable.erase(x);
        } else if (op == 3) {
            bool exists = hashTable.contains(x);
            g << exists << std::endl;
        }
    }

    return 0;
}