Cod sursa(job #3131012)

Utilizator dariutTache Daria dariut Data 19 mai 2023 00:22:14
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.67 kb
#include <iostream>
#include <fstream>

struct Node {
    int value = -1;
    Node* next = nullptr;
};

class Hash {
private:
    Node* hash[87129];
public:
    Hash() {
        for (int i = 0; i < 87129; i++)
            hash[i] = nullptr;
    }

    void insert(int value) {
        int index = value % 87129;
        if (hash[index] == nullptr) {
            hash[index] = new Node;
            hash[index]->value = value;
        }
        else {
            Node* ptr = hash[index];
            while (ptr->next != nullptr && ptr->value != value)
                ptr = ptr->next;
            if (ptr->value != value) {
                ptr->next = new Node;
                ptr->next->next = nullptr;
                ptr->next->value = value;
            }
        }
    }

    void remove(int value) {
        int index = value % 87129;
        Node* ptr;
        if (hash[index] != nullptr && hash[index]->value == value) {
            ptr = hash[index]->next;
            delete hash[index];
            hash[index] = ptr;
        }
        else if (hash[index] != nullptr && hash[index]->value != value && hash[index]->next != nullptr) {
            ptr = hash[index];
            int ok = 0;
            while (ptr->value != value && ptr->next != nullptr) {
                if (ptr->next->value == value) {
                    ok = 1;
                    break;
                }
                ptr = ptr->next;
            }
            if (ok == 1) {
                Node* ptr2 = ptr->next->next;
                delete ptr->next;
                ptr->next = ptr2;
            }
        }
    }

    int find(int value) {
        int index = value % 87129;
        Node* ptr = hash[index];
        while (ptr != nullptr && ptr->value != value)
            ptr = ptr->next;
        if (ptr != nullptr)
            return 1;
        return 0;
    }

    void clear() {
        for (int i = 0; i < 87129; i++) {
            while (hash[i] != nullptr)
                remove(hash[i]->value);
        }
    }
};

int main() {
    std::ifstream f("hashuri.in");
    std::ofstream g("hashuri.out");

    int operation, value, n, ok = 0;
    Hash table;

    f >> n;
    while (n > 0) {
        f >> operation >> value;
        switch (operation) {
        case 1:
            table.insert(value);
            break;
        case 2:
            table.remove(value);
            break;
        case 3:
            if (ok)
                g << '\n';
            g << table.find(value);
            ok = 1;
            break;
        }
        n--;
    }

    table.clear();

    f.close();
    g.close();

    return 0;
}