Cod sursa(job #1173327)

Utilizator mihai995mihai995 mihai995 Data 19 aprilie 2014 09:39:10
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.23 kb
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

const int nil = 0x3f3f3f3f;
const double maxLoadFactor = 0.6;

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

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

    inline static int nextPrime(int x){
        int i = 2;
        while ( i * i <= x && x % i )
            i++;
        return ( i * i > x ) ? x : nextPrime(x + 1);
    }

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

        int poz = x % cap, step = 1 + x % mod;

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

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

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

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

    inline void swap(HashTable& H){
        HashTable aux = H;
        H = *this;
        *this = aux;
        aux.hash = NULL;
    }

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