Cod sursa(job #911063)

Utilizator chimistuFMI Stirb Andrei chimistu Data 11 martie 2013 12:16:26
Problema Hashuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.73 kb
#include <iostream>
#include <fstream>
#include <ctime>

using namespace std;

class cuckoo_hash
{
    int k;
    int *hash1;
    int *hash2;
    int a,b;
public:
    cuckoo_hash();
    ~cuckoo_hash();
    int functie_hash1(int);
    int functie_hash2(int);
    void randomizare();
    bool cauta(int);
    bool insereaza(int);
    void sterge(int);
};

cuckoo_hash::cuckoo_hash()
{
    hash1 = new int[1000001];
    hash2 = new int[1000001];
    k=666013;
    randomizare();
    for (int i=0;i<1000001;i++)
    {
        hash1[i]=0;
        hash2[i]=0;
    }
}

cuckoo_hash::~cuckoo_hash()
{
    delete[] hash1;
    delete[] hash2;
}

void cuckoo_hash::randomizare()
{
    a=rand() % 1000001;
    b=rand() % 1000001;
}

int cuckoo_hash::functie_hash1(int x)
{
    return (a % k * (x)%k);
}

int cuckoo_hash::functie_hash2(int x)
{
    return (b+ ((x) % k));
}

bool cuckoo_hash::cauta(int x)
{
    int f1 = functie_hash1(x);
    int f2 = functie_hash2(x);
    if (hash1[f1] == x || hash2[f2] == x)
        return true;
    else
        return false;
}

void cuckoo_hash::sterge(int x)
{
    int f1 = functie_hash1(x);
    int f2 = functie_hash2(x);
    if (hash1[f1] == x)
        hash1[f1] = 0;
    else
        if (hash2[f2] == x)
            hash2[f2] = 0;
}

bool cuckoo_hash::insereaza(int x)
{
    if (cauta(x))
        return true;
    else
    {
        int f1 = functie_hash1(x);
        int f2 = functie_hash2(x);
        int i=0,aux;
        while (i<3)
        {
            if (hash1[f1] == 0)
            {
                hash1[f1] = x;
                i=5;
                return true;
            }
            aux = hash1[f1];
            hash1[f1] = x;
            x = aux;
            if (hash2[f2] == 0)
            {
                hash2[f2] = x;
                i=5;
                return true;
            }
            aux = hash2[f2];
            hash2[f2] = x;
            x = aux;
            i++;
        }
    }
}


int main()
{
    srand(time(NULL));
    cuckoo_hash q;
    bool da = false;
    while (!da)
    {
        ifstream f("hashuri.in");
        ofstream g("hashuri.out");
        int n,op,val;
        f >> n;
        for (int i=0;i<n;i++)
        {
            f >> op >> val;
            if (op==1)
            {
                if (!q.insereaza(val))
                {
                    da = false;
                    break;
                }
            }
            if (op == 2)
            {
                q.sterge(val);
            }
            if (op == 3)
            {
                g << (int) q.cauta(val) << "\n";
            }
        }
        da = true;
    }
    return 0;
}