Cod sursa(job #739622)

Utilizator sternvladStern Vlad sternvlad Data 23 aprilie 2012 16:17:59
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.15 kb
#include <stdio.h>
#include <fstream>

const int M1=1022467;
const int M2=1022449;

using namespace std;


template <class Type>
class hash{
	Type *T;
	char *nu_exista;
	char *folosit;

	int f(Type,int);

public:
    hash();
    ~hash();
	int query(Type x);
    int insert(Type x);
	int remove(Type x);
};




template <class Type>
hash<Type>::hash()
	{
		T=new Type[M1];
		nu_exista=new char[M1];
		folosit=new char[M1];
		for (int i=0;i<M1;i++){
			T[i]=0;
			nu_exista[i]=0;
			folosit[i]=0;
		}
	}


template <class Type>
hash<Type>::~hash()
	{
		delete[] T;
		delete[] nu_exista;
		delete[] folosit;
	}


template <class Type>
int hash<Type>::query(Type x)
	{
		int t;
		for(int i=0;;i++){
			t=f(x,i);
			if (folosit[t]==0) return 0;
			if (T[t]==x && !nu_exista[t]) return 1;
		}
		return 0;
	}


template <class Type>
int hash<Type>::insert (Type x)
{
		int i,temp,j;
		for (i=0;temp=f(x,i), folosit[temp]&&(T[temp]!=x||nu_exista[temp])&&(i<M2); i++);
				if (T[temp]==x && folosit[temp]) return -1;
		for (j=0;folosit[f(x,j)]&&!nu_exista[f(x,j)];j++);
		T[f(x,j)]=x;
		nu_exista[f(x,j)]=0;
		folosit[f(x,j)]=1;
		return f(x,j);
	}


template <class Type>
int hash<Type>::remove (Type x)
{
		int temp;
		for(int i=0;;i++){
			temp=f(x,i);
			if (!folosit[temp]) return -1;
			if (T[temp]==x && !nu_exista[temp]){
				nu_exista[temp]=1;
				return temp;
			}

		}
}
template<class Type>
 int hash<Type>::f(Type x, int i){
	int integer=(int)x;
	int fract=int(1000*(x-integer));
	return ((((integer+fract)%M1)+i*(1+(integer+fract)%M2))%M1);
}

template<>
 int hash<char *>::f(char *str, int i)
{
	 int x = 5381;
	int c;
	while ((c = *str++))
		x = ((x << 5) + x) + c;
	return (((x%M1)+i*(1+x%M2))%M1);
}

int main()
{
	int n;
	hash< int> has;
	int operation,number;
    ifstream in ("hashuri.in");
    ofstream out ("hashuri.out");
    in>>n;
	for (register int i=1;i<=n;i++){
		in>>operation>>number;

		if (operation==1){ has.insert(number); continue;}
		if (operation==2){ has.remove(number); continue;}
		if (operation==3) out<<has.query(number)<<"\n";
	}
	return 0;
}