Cod sursa(job #1527886)

Utilizator Mihai22eMihai Ionut Enache Mihai22e Data 18 noiembrie 2015 20:04:47
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.32 kb
#include <fstream>
using namespace std;

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

        Node() {
            value = -1;
            next = NULL;
        }
};

class Hash {
    private:
        const int  MOD = 666013;
        Node **h = new Node* [MOD];

    public:
        void insertValue(int x) {
            int l = x % MOD;

            if(h[l] == NULL) {
                h[l] = new Node;
            }
            Node *node = h[l];

            while(node->next != NULL) {
                if(node->value == x) {
                    return;
                }
                node = node->next;
            }

            node->value = x;

            Node *tmp = new Node;
            node->next = tmp;
        }

        void deleteValue(int x) {
            int l = x % MOD;

            if(h[l] == NULL) {
                return;
            }
            Node *node = h[l];

            if(node->value == x) {
                h[l] = node->next;
                delete node;
            }
            else {
                while(node->next && node->next->value != x) {
                    node = node->next;
                }

                if(node->next != NULL) {
                    Node *tmp = node->next;
                    node->next = node->next->next;
                    delete tmp;
                }
            }
        }

        bool searchValue(int x) {
            int l = x % MOD;

            if(h[l] == NULL) {
                return false;
            }
            Node *node = h[l];

            while(node->next != NULL && node->value != x) {
                node = node->next;
            }

            if(node->value == x) {
                return true;
            }
            else {
                return false;
            }
        }

        Hash() {
            for(int i = 0; i < MOD; ++i) {
                h[i] = NULL;
            }
        }
};

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

    int n;
    f >> n;

    Hash h;
    for(int i = 0; i < n; ++i) {
        int op, x;

        f >> op >> x;
        if(op == 1) {
            h.insertValue(x);
        }
        else if(op == 2) {
            h.deleteValue(x);
        }
        else if(op == 3) {
            g << h.searchValue(x) << "\n";
        }
    }

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

    return 0;
}