Cod sursa(job #714304)

Utilizator AnaTudorTudor Ana Maria Mihaela AnaTudor Data 15 martie 2012 17:39:11
Problema Hashuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <stdio.h>

const int M1 = 666013, M2 = 100021, M3 = 100007;
const char infile[] = "hashuri.in", outfile[] = "hashuri.out";

class hash {
	private:
		int *H;
		int hash_size;
	public:
		hash( int size ) {
			hash_size = size;
			H = new int[ 2*hash_size ];
		}

		void insert( int key );
		int search( int key );
		void erase( int key );
		int first_hash( int key );
		int second_hash( int key );
		int do_hash( int key, int i );
} ;

int hash::first_hash( int key ) {
	return key % M2;
}

int hash::second_hash( int key ) {
	return 1 + ( key % M3 );
}

int hash::do_hash( int key, int i ) {
	return ( first_hash( key ) + i * second_hash( key ) ) % M1;
}

int hash::search( int key ) {
	int i, j;
	for( i = 0; i < hash_size; ++i ) {
		j = do_hash( key, i );
		if (H[j]==0)
		return -1;
		if( H[ j ] == key )
			return j;
	}
	return -1;
}

void hash::insert( int key ) {
	int i, j;
	if( search( key ) == -1 )
		for( i = 0; i < hash_size; ++i ) {
			j = do_hash( key, i );
			if( H[ j ] == 0 ) {
				H[ j ] = key;
				return;
			}
		}
}

void hash::erase( int key ) {
	int j = search( key );
	if( j != -1 )
		H[ j ] = 0;
}

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