Cod sursa(job #1070533)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 1 ianuarie 2014 15:15:11
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const unsigned FNV_offset_basis = 2166136261;
const unsigned FNV_prime = 16777619;

const unsigned MASK_16 = ( 1 << 16 );

unsigned fhash( char *key, int len )
{
    unsigned hsh = FNV_offset_basis;

    while ( len-- )
    {
        hsh = hsh ^ *key;
        hsh = hsh * FNV_prime;
        key++;
    }

    return ( hsh >> 16 ) ^ ( hsh & MASK_16 );
}

vector <unsigned> HT[MASK_16];

unsigned fhash( unsigned x )
{
    unsigned hsh = FNV_offset_basis;
    hsh = hsh ^ x;
    hsh = hsh * FNV_prime;
    return ( hsh >> 16 ) ^ ( hsh & ( MASK_16 - 1 ) );
}

bool find( unsigned value )
{
    unsigned key = fhash( value );

    for ( auto x: HT[key] )
            if ( x == value )
                    return 1;

    return 0;
}

void insert( unsigned value )
{
    unsigned key = fhash( value );

    if ( !find( value ) )
            HT[key].push_back( value );
}

void erase( unsigned value )
{
    unsigned key = fhash( value );

    for ( vector<unsigned>::iterator x = HT[key].begin(); x != HT[key].end(); ++x )
            if ( *x == value )
            {
                HT[key].erase( x );
                break;
            }
}

int N;
unsigned key, type;

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

    f >> N;

    while ( N-- )
    {
        f >> type >> key;

        if ( type == 1 ) insert( key );
        if ( type == 2 ) erase( key );
        if ( type == 3 ) g << find( key ) << "\n";
    }

    return 0;
}