Cod sursa(job #2491191)

Utilizator TooHappyMarchitan Teodor TooHappy Data 11 noiembrie 2019 23:44:57
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.4 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("hashuri.in");
ofstream out("hashuri.out");

const int MOD = 666013;

class HashNode {
public:
    int value;
    HashNode *next;

    HashNode(int value) : value(value), next(nullptr) { }
};

class HashMap {
private:
    HashNode **table;
    int capacity;

    int hashCode(int key) {
        return key % MOD;
    }

public:
    HashMap() : capacity(MOD) {
        table = new HashNode *[MOD]();
    }

    ~HashMap() {
        for (int i = 0; i < capacity; ++i) {
            HashNode *entry = table[i];

            while (entry != nullptr) {
                HashNode *prev = entry;
                entry = entry->next;

                delete prev;
            }

            table[i] = nullptr;
        }

        delete[] table;
    }

    void insert(int value) {
        int hashIndex = hashCode(value);
        HashNode *prev = nullptr;
        HashNode *entry = table[hashIndex];

        while (entry != nullptr && entry->value != value) {
            prev = entry;
            entry = entry->next;
        }

        if (entry == nullptr) {
            entry = new HashNode(value);

            if (prev == nullptr) {
                table[hashIndex] = entry;
            } else {
                prev->next = entry;
            }
        }
    }

    void remove(int value) {
        int hashIndex = hashCode(value);
        HashNode *prev = nullptr;
        HashNode *entry = table[hashIndex];

        while (entry != nullptr && entry->value != value) {
            prev = entry;
            entry = entry->next;
        }

        if (entry == nullptr) {
            return;
        } else {
            if (prev == nullptr) {
                table[hashIndex] = entry->next;
            } else {
                prev->next = entry->next;
            }

            delete entry;
        }
    }

    bool find(int value) {
        int hashIndex = hashCode(value);
        HashNode *entry = table[hashIndex];

        while (entry != nullptr && entry->value != value) {
            entry = entry->next;
        }

        return (entry != nullptr);
    }
};

int main() {
    int n; in >> n;

    HashMap hMap;
    for (int i = 1; i <= n; ++i) {
        int op, x; in >> op >> x;

        if (op == 1) {
            hMap.insert(x);
        } else if (op == 2) {
            hMap.remove(x);
        } else {
            out << hMap.find(x) << "\n";
        }
    }

    return 0;
}