Cod sursa(job #905759)

Utilizator cdascaluDascalu Cristian cdascalu Data 6 martie 2013 09:39:10
Problema Hashuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.64 kb
#include <fstream>
#include <iostream>
#include <vector>
#define Nmax 2000000
using namespace std;

class FNV_Hash
{
    public:

        FNV_Hash(unsigned int size);
        ~FNV_Hash();

        unsigned int       hash_function(int elem);
        void                insert_element(int elem);
        void                remove_element(int elem);
        bool                check_element(int elem);
    private:

        unsigned int             hash_size;
        unsigned int             FNV_prime;
        unsigned int             FNV_init;

        vector<int>               hash_vector[Nmax];
};
int main()
{
    FNV_Hash *my_hash;
    my_hash = new FNV_Hash(Nmax);

    ifstream f("hashuri.in");
    ofstream g("hashuri.out");
    int N,op,val;
    f>>N;
    while(N--)
    {
        f>>op>>val;
        if(op == 3)
        {
            if(my_hash->check_element(val))
                g<<"1\n";
            else g<<"0\n";
        }
        else if(op == 2)
        {
            my_hash->remove_element(val);
        }
        else if(op == 1)
        {
            my_hash->insert_element(val);
        }
    }
    f.close();
    g.close();

    delete my_hash;
    my_hash = 0;
    return 0;
}

FNV_Hash::FNV_Hash(unsigned int size)
{
    hash_size               = size;
    FNV_prime               = 16777619;
    FNV_init                = 2166136261;
}
FNV_Hash::~FNV_Hash()
{
    ;
}
unsigned int FNV_Hash::hash_function(int elem)
{
    int last_part, return_value;

    for(return_value = FNV_init;elem;elem/=10)
    {
        last_part           = elem%10;
        return_value        = return_value ^ char(last_part + 'a');
        return_value        = return_value * FNV_prime;
    }
    return return_value;
}

void FNV_Hash::insert_element(int elem)
{
    unsigned int hash_key       = hash_function(elem) % hash_size;

    for(vector<int>::iterator it = hash_vector[hash_key].begin();it!=hash_vector[hash_key].end();++it)
    {
        if(*it == elem)
            return;
    }
    hash_vector[hash_key].push_back(elem);
}

void FNV_Hash::remove_element(int elem)
{
    unsigned int hash_key       = hash_function(elem) % hash_size;

    for(vector<int>::iterator it = hash_vector[hash_key].begin();it!=hash_vector[hash_key].end();++it)
    {
        if(*it == elem)
        {
            hash_vector[hash_key].erase(it);
            return;
        }
    }
}

bool FNV_Hash::check_element(int elem)
{
    unsigned int hash_key       = hash_function(elem) % hash_size;

    for(vector<int>::iterator it = hash_vector[hash_key].begin();it!=hash_vector[hash_key].end();++it)
    {
        if(*it == elem)
        {
            return true;
        }
    }
    return false;
}