Cod sursa(job #3131157)

Utilizator z.catincaCatinca Zavoianu z.catinca Data 19 mai 2023 13:04:55
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <list>

const int TABLE_SIZE = 1000003;

class HashTable {
private:
    std::vector<std::list<int>> table;

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

public:
    HashTable() {
        table.resize(TABLE_SIZE);
    }

    void add(int key) {
        int index = hashFunction(key);
        std::list<int>& bucket = table[index];

        for (int element : bucket) {
            if (element == key) {
                return;  // Element already exists, no need to add it again
            }
        }

        bucket.push_back(key);
    }

    void remove(int key) {
        int index = hashFunction(key);
        std::list<int>& bucket = table[index];

        for (auto it = bucket.begin(); it != bucket.end(); ++it) {
            if (*it == key) {
                bucket.erase(it);
                return;
            }
        }
    }

    bool exists(int key) {
        int index = hashFunction(key);
        std::list<int>& bucket = table[index];

        for (int element : bucket) {
            if (element == key) {
                return true;
            }
        }

        return false;
    }
};

int main() {
    std::ifstream inputFile("hashuri.in");
    std::ofstream outputFile("hashuri.out");

    int N;
    inputFile >> N;

    HashTable hashTable;

    for (int i = 0; i < N; i++) {
        int op, x;
        inputFile >> op >> x;

        switch (op) {
            case 1:
                hashTable.add(x);
                break;
            case 2:
                hashTable.remove(x);
                break;
            case 3:
                outputFile << (hashTable.exists(x) ? 1 : 0) << '\n';
                break;
            default:
                break;
        }
    }

    inputFile.close();
    outputFile.close();

    return 0;
}