Cod sursa(job #714372)

Utilizator andumMorie Daniel Alexandru andum Data 15 martie 2012 18:17:37
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.79 kb
#include <fstream>

using namespace std;

class element
{
    public:

    int info;
    element *next;
};

class hash_table
{
    element *q;
    int Size;

    public:
        hash_table();

        void insert(int);
        void erase(int);
        bool empty();
        bool find(int);
        int size();
        element* first();
        element* last();
};

hash_table::hash_table()
{
    q = NULL;
    Size = 0;
}

bool hash_table::empty()
{
    if (Size)
        return false;
    return true;
}

int hash_table::size()
{
    return Size;
}

element* hash_table::first()
{
    return q;
}

element* hash_table::last()
{
    element *p;
    p=q;
    while (p->next != NULL)
        p=p->next;
    return p;
}

bool hash_table::find(int x)
{
    element *p;
    //if (empty())
    //    return false;
    p = first();
    while (p != NULL)
    {
        if (p->info == x)
            return true;
        p = p->next;
    }
    return false;
}

void hash_table::insert(int x)
{
    element *p,*newnode;
    if (find(x))
        return;

    newnode = new element;
    newnode->info = x;
    newnode->next = NULL;

    if (empty())
    {
        q = newnode;
    }
    else
    {
        p = last();
        p->next = newnode;
    }

    Size++;
}

void hash_table::erase(int x)
{
    element *p, *u;
    if (!find(x))
        return;

    if (Size == 1)
    {
        q = NULL;
    }
    else
    {
        u = first();
        p = u->next;
        while (p != NULL)
        {
            if (p->info == x)
            {
                u->next = p->next;
                delete p;
                break;
            }
            u = p;
            p = p->next;
        }
    }

    Size--;
}

class hash
{
    hash_table *tables;
    int P;

    public:
        hash();

        void insert(int);
        void erase(int);
        short int find(int);

};

hash::hash()
{
    P = 393241;
    tables = new hash_table[P];
}

void hash::insert(int x)
{
    int table = x%P;

    tables[table].insert(x);
}

void hash::erase(int x)
{
    int table = x%P;

    tables[table].erase(x);
}

short int hash::find(int x)
{
    int table = x%P;

    if (tables[table].find(x))
        return 1;
    return 0;
}


int main()
{
    int n,op,x;
    ifstream in("hashuri.in");
    ofstream out("hashuri.out");

    hash H;
    in>>n;
    for (; n; --n)
    {
        in>>op>>x;
        switch (op)
        {
            case 1:
                H.insert(x);
                break;
            case 2:
                H.erase(x);
                break;
            case 3:
                out<<H.find(x)<<'\n';
                break;
        }
    }

    return 0;
}