Cod sursa(job #1173024)

Utilizator mihai995mihai995 mihai995 Data 18 aprilie 2014 14:34:30
Problema Hashuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <fstream>
#include <cstdlib>
using namespace std;

const int nil = 0x3f3f3f3f, mod1 = 1046527, mod2 = 666013;
const double maxLoadFactor = 0.45;

class HashTable{
    int* hash;
    int size, cap;

    template<class Type>
    inline static void swap(Type& a, Type& b){
        Type c = a;
        a = b;
        b = c;
    }

    int lookup(int x){
        if ( maxLoadFactor * cap < size ){
            HashTable H(cap << 1);
            for (int i = 0 ; i < cap ; i++)
                if ( hash[i] && hash[i] != nil )
                    H.insert( hash[i] );
            H.swap(*this);
        }

        int poz = (x % mod1) & (cap - 1), step = x % mod2 % (cap - 1);

        if (step == 0) step = 1;

        while ( hash[poz] && hash[poz] != x )
            poz = (poz + step) & (cap - 1);

        return poz;
    }
public:
    HashTable(){
        hash = (int*)calloc(2, sizeof(int));
        cap = 2;
        size = 0;
    }

    HashTable(int n){
        hash = (int*)calloc(n, sizeof(int));
        cap = n;
        size = 0;
    }

    inline void swap(HashTable& H){
        swap(hash, H.hash);
        swap(size, H.size);
        swap(cap, H.cap);
    }

    void insert(int x){
        int poz = lookup(x);
        if ( hash[poz] != x ){
            hash[poz] = x;
            size++;
        }
    }

    bool contains(int x){
        int poz = lookup(x);
        return hash[poz] == x;
    }

    void erase(int x){
        int poz = lookup(x);
        if (hash[poz] == x){
            hash[poz] = nil;
            size--;
        }
    }

    ~HashTable(){
        free(hash);
    }
};

int main(){
    int times, tip, x;
    HashTable H;

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

    in >> times;
    while (times--){
        in >> tip >> x;

        if (tip == 1)
            H.insert(x);
        if (tip == 2)
            H.erase(x);
        if (tip == 3)
            out << H.contains(x) << '\n';
    }

    in.close();
    out.close();

    return 0;
}