Cod sursa(job #744770)

Utilizator JohannesJohannes Dragulanescu Johannes Data 9 mai 2012 17:09:32
Problema Hashuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
//Hashing Dragulanescu Val-Johannes Gr.135
//h(x) = (h'(x) + rand1 * i + rand2 * i^2) % M
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <iostream>
#include <string.h>
#define NMAX 1000
using namespace std;

template <class T>
class Hash
{
	private:
		int rand1,rand2;
		bool *sters; //vector pentru elementele sterse
		T *v; //vectorul pt hashing
		int n;
		int hash_function(T,int);
	public:
		Hash (int k)
		{
			n=k;
			//vectorul
			v = new T[NMAX];
			sters = new bool [NMAX];
			memset (v,0,sizeof(v)*NMAX);
			//initializam 2 valori random pt functia de hash

			/* initialize random seed: */
			srand ( time(NULL) );

			/* generate number: */
			rand1=rand()%NMAX;
			rand2=rand()%NMAX;
		}
		~Hash () 
		{
			delete[] v;
		}
		
		void hash_insert(T x)
		{
			int k=0;
			while (v[hash_function(x,k)]!=0 && k<=NMAX)
				k++;
			if (k>=n+1) 
			{
				cout<<"Vectorul este plin!"; 
				return;
			}
			v[hash_function(x,k)]=x;
			sters[hash_function(x,k)]=0;
		}
		
		void hash_delete(T x)
		{
			int k=0;
			while (v[hash_function(x,k)]!=x && (v[hash_function(x,k)]!=0 || sters[hash_function(x,k)]==1) && k<=NMAX) 
				k++;
			if (v[hash_function(x,k)]==0) return;
			else if (k<=n) 
			{
				v[hash_function(x,k)]=0;
				sters[hash_function(x,k)]=1;
			}
		}
		
		bool hash_search(T x)
		{
			int k=0;
			while (v[hash_function(x,k)]!=x && (v[hash_function(x,k)]!=0 || sters[hash_function(x,k)]==1) && k<=NMAX) 
				k++;
			if (k<=n && v[hash_function(x,k)]==x) return 1;
			else return 0;
		}
		
};

template <class T>
int Hash <T>::hash_function(T x, int i)
{
	int rez=abs((x%NMAX+rand1*i+rand2*i*i))%NMAX;
	return rez;
}

template<>
int Hash <char *>::hash_function(char *str, int i)
{
	unsigned long  x = 5381;	//O metoda a algoritmului lui Dan Bernstein prin care calculez valuarea de hash pentru stringuri http://www.cse.yorku.ca/~oz/hash.html
	int c;
	while ((c = *str++))
		x = ((x << 5) + x) + c;
	return abs((x%NMAX+rand1*i+rand2*i*i))%NMAX;
}

int main ()
{
	ifstream fin ("hashuri.in");
	ofstream fout ("hashuri.out");
	int op,n;
	
	fin>>n;
	Hash <int> h(n);
	int x;
	
	for (int i=1;i<=n;i++)
	{ 
		fin>>op>>x;

		if (op==1) 
		{
			if (!h.hash_search(x))  
				h.hash_insert(x); 
		}
		else if (op==2) h.hash_delete(x);
		else if (op==3) fout<<h.hash_search(x)<<'\n';
	}
	fin.close();
	fout.close();
	return 0;
}