Cod sursa(job #739608)

Utilizator sternvladStern Vlad sternvlad Data 23 aprilie 2012 16:07:19
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 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;

	unsigned int f(Type,int);

public:
	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;
		}
	}
	~hash()
	{
		delete[] T;
		delete[] nu_exista;
		delete[] folosit;
	}

	int 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;
	}
	unsigned int insert(Type x)
	{
		unsigned 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);
	}
	unsigned int remove(Type x)
	{
		unsigned 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>
unsigned int hash<Type>::f(Type x, int i){
	int intreaga=(int)x;
	int fract=int(1000*(x-intreaga));
	return ((((intreaga+fract)%M1)+i*(1+(intreaga+fract)%M2))%M1);
}

template<>
unsigned int hash<char *>::f(char *str, int i)
{
	unsigned 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<unsigned int> has;
	ifstream in ("hashuri.in");
	ofstream out ("hashuri.out");
	unsigned int operation,number;

    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;
}