Cod sursa(job #1477588)

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

using namespace std;

template <const size_t MAX_SIZE>
class LinearProbing
{
private:

    static const int NIL = -1;
    static const int DELETED = -2;

    int table[MAX_SIZE];

    inline bool check(const size_t pos, const int key) const
    {
        return table[pos] != NIL && table[pos] != key;
    }

    size_t h1(const int key) const
    {
        return (1U * key) * 2654435761;
    }

    size_t h2(const int key) const
    {
        unsigned a = key;

        a += ~(a<<15);
        a ^=  (a>>10);
        a +=  (a<<3);
        a ^=  (a>>6);
        a += ~(a<<11);
        a ^=  (a>>16);

        return a;
    }

    int supposedPosition(const int key) const
    {
        size_t pos = 0;

        while (check((h1(key) + pos * h2(key)) % MAX_SIZE, key) == true)
            pos++;

        return (h1(key) + pos * h2(key)) % MAX_SIZE;
    }

public:

    LinearProbing()
    {
        for (int i = 0; i < MAX_SIZE; ++i)
            table[i] = NIL;
    }

    void insert(const int key)
    {
        table[supposedPosition(key)] = key;
    }

    bool find(const int key)
    {
        return table[supposedPosition(key)] == key;
    }

    void erase(const int key)
    {
        int pos = supposedPosition(key);

        if (table[pos] == key)
            table[pos] = DELETED;
    }
};

const int M = 1 << 20;

LinearProbing<M> L;

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

    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;
        }
    }

    return 0;
}