Cod sursa(job #1477462)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 26 august 2015 13:05:50
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>

using namespace std;

const double A = 0.6180339887;

class LinearProbing
{
public:

    LinearProbing()
    {
        table = new int[MAX_SIZE];

        for ( int i = 0; i < MAX_SIZE; ++i )
            table[i] = EMPTY;
    }

    ~LinearProbing()
    {
        delete[] table;
    }

    double fhash(const int key)
    {
        double k = 1.0 * key * A - 1.0 * ((int)(1.0 * key * A));
        return (int)(1.0 * k * MAX_SIZE);
    }

    void insert(const int key)
    {
        int p = fhash(key);

        while (table[p] != EMPTY && table[p] != ERASED)
            p = (p + 1) & MOD;

        table[p] = key;
    }

    bool find(const int key)
    {
        int p = fhash(key);

        while (table[p] != EMPTY && table[p] != key)
            p = (p + 1) & MOD;

        return table[p] == key;
    }

    void erase(const int key)
    {
        int p = fhash(key);

        while (table[p] != EMPTY && table[p] != key)
            p = (p + 1) & MOD;

        if (table[p] == key)
            table[p] = ERASED;
    }

private:

    static const int MAX_SIZE = 1 << 20;
    static const int MOD = MAX_SIZE - 1;
    static const int PRIME = 137;

    static const int EMPTY = -1;
    static const int ERASED = -2;

    int *table;
};

LinearProbing L;

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

    ios_base::sync_with_stdio( false );

    int N;
    in >> N;

    while ( N-- )
    {
        int tip, x;

        in >> tip >> x;

        switch(tip)
        {
            case 1: L.insert(x); break;
            case 2: L.erase(x); break;
            case 3: out << L.find(x) << "\n"; break;

            default: cerr << "Error\n";
        }
    }

    return 0;
}