Cod sursa(job #3230718)

Utilizator Razvan23Razvan Mosanu Razvan23 Data 22 mai 2024 16:19:01
Problema Hashuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.44 kb
#include <bits/stdc++.h>
#define P 1234577
using namespace std;

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


struct Nod
{
    int key;
    int val;
    Nod *ant, *urm;
    Nod(int key, int val)
    {
        this->val = val;
        this->key = key;
        ant = urm = NULL;
    }
};

class HashTable
{
public :
    Nod **H, **head;
    int n;
    HashTable(int n)
    {
        this->n = n;
        H = new Nod * [n];
        head = new Nod * [n];
        for(int i = 0; i < n; i++)
            H[i] = head[i] = NULL;
    }
    ~HashTable()
    {
        delete[] H;
        delete[] head;
    }
    int Modulo(int x)
    {
        return x % n;
    }
    virtual void Insert(int index, int x)
    {
        int nr = Modulo(index);
        Nod *p = H[nr];
        if(p == NULL)
        {
            p = new Nod(index, x);
            H[nr] = p;
            head[nr] = p;
        }
        else
        {
            while(p != NULL)
                p = p->urm;
            p = new Nod(index, x);
            p->ant = head[nr];
            head[nr]->urm = p;
            head[nr] = p;
        }
    }
    virtual void Search(int index)
    {
        int nr = Modulo(index);
        Nod *p = H[nr];
        if(p != NULL)
        {
            while(p != NULL && p->key != nr)
                p = p->urm;
            if(p != NULL)
            {
                index = p->val;
                fout << "1\n";
                return;
            }
        }
        fout << "0\n";
    }
    virtual void Remove(int index)
    {
        int nr = Modulo(index);
        Nod *p = H[nr];
        if(p == NULL || p->key != index) return;
        while(p != NULL)
        {
            if(p->urm == NULL)
            {
                if(p->ant == NULL)
                {
                    head[nr] = H[nr] = NULL;
                    delete p;
                    return;
                }
            }
            else
            {
                head[nr] = p->ant;
                head[nr]->urm = NULL;
                delete p;
                p = head[nr];
            }
            p = p->urm;
        }
    }

};


int main()
{
    int n, i, x, op;
    fin >> n;
    HashTable A(P);
    for(i=1;i<=n;i++)
    {
        fin >> op >> x;
        if(op == 1) A.Insert(x, x);
        else if(op == 2) A.Remove(x);
        else A.Search(x);
    }
    return 0;
}