Cod sursa(job #714440)

Utilizator AnaTudorTudor Ana Maria Mihaela AnaTudor Data 15 martie 2012 19:12:16
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.43 kb
#include <stdio.h>
#include <stdlib.h>
#define ll long long
using namespace std;

const char infile[] = "hashuri.in", outfile[] = "hashuri.out";
int T, operation, key;

class cuckooHash {
	private:
		ll *T1, *T2;
		int upper_bound, step, table_size;
		int a1, a2, b1, b2;
		ll p;

	public:
		cuckooHash( int size );
		void insert( int key );
		void erase( int key );
		ll search( int key, int &sw );
		ll hash1( int key );
		ll hash2( int key );
		void swap( ll &a, ll &b );
} ;

cuckooHash::cuckooHash( int size ) {
	table_size = size;
	T1 = new ll[ size ];
	T2 = new ll[ size ];
	a1 = 1 + rand() % size;
	b1 = rand() % size;
	a2 = 1 + rand() % size;
	b2 = rand() % size;
	p = 2000000011;
	upper_bound = table_size / 2;
	step = 0;
	int i;
	for( i = 0; i < size; ++i )
		T1[ i ] = T2[ i ] = 0;
}

ll cuckooHash::hash1( int key ) {
	return ( (long long)( a1 * (ll)key + b1 ) % p ) % (ll)table_size;
}

ll cuckooHash::hash2( int key ) {
	return ( (long long)( a2 * (ll)key + b2 ) % p ) % (ll)table_size;
}

void cuckooHash::swap( ll &a, ll &b ) {
	ll aux = a;
	a = b; b = aux;
}

ll cuckooHash::search( int key, int &sw ) {
	ll  position = hash1( key );
	if( T1[ position ] == key ) {
		sw = 1;
		return position;
	}
	position = hash2( key );
	if( T2[ position ] == key ) {
		sw = -1;
		return position;
	}
	return -1;
}

void cuckooHash::insert( int key ) {
	ll value = hash1( key ), aux;
	int sw=1;
	if( search( key, sw ) != -1 )
		return;
	if( T1[ value ] == 0 ) {
		T1[ value ] = key;
		return;
	}
     sw=1;
     step=0;
	aux = T1[ value ];
	T1[ value ] = key;
	while( aux != 0 && step < upper_bound ) {
		if( sw == 1 ) {
			value = hash2( aux );
			swap( aux, T2[ value ] );
		}
		else {
			value = hash1( aux );
			swap( aux, T1[ value ] );
		}
		step ++;
		sw *= -1;
	}
}


void cuckooHash::erase( int key ) {
	int  sw;
	ll position = search( key, sw );
	if( position == -1 )
		return;
	if( sw == 1 )
		T1[ position ] = 0;
	else
		T2[ position ] = 0;
}

int main() {
	freopen( infile, "r", stdin );
	freopen( outfile, "w", stdout );
	scanf( "%d", &T );
	cuckooHash O( 1000005 );
	for( ; T; T-- ) {
		scanf( "%d %d", &operation, &key );
		if( operation == 1 )
			O.insert( key );
		if( operation == 2 )
			O.erase( key );
		if( operation == 3 )
			printf( "%d\n", O.search( key, operation ) == -1 ? 0 : 1 );
	}
	fclose( stdin );
	fclose( stdout );
	return 0;
}